Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace Temp
{
public class Program
{
public static void Main(string[] args)
{
using (var ctx = new MyClass())
{
ctx.Database.CreateIfNotExists();
if (!ctx.Companies.Any())
{
var company = ctx.Companies.Create();
company.AddUnits();
ctx.Companies.Add(company);
ctx.SaveChanges();
}
}
using (var ctx = new MyClass())
{
var company = ctx.Companies.Find(1);
Console.WriteLine(company.BusinessUnits?.Count);
}
}
}
public class Company
{
public virtual ICollection<BusinessUnit> BusinessUnits { get; protected set; }
public int Id { get; protected set; }
public void AddUnits()
{
BusinessUnits = new List<BusinessUnit> { new BusinessUnit(this, "Desc") };
}
}
public class BusinessUnit
{
public BusinessUnit()
{
}
public BusinessUnit(Company company, string description)
{
Company = company;
Description = description;
}
public int Id { get; protected set; }
public virtual Company Company { get; protected set; }
public int CompanyId { get; protected set; }
public string Description { get; protected set; }
}
public class MyClass : DbContext
{
public DbSet<Company> Companies { get; set; }
public DbSet<BusinessUnit> BusinessUnits { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BusinessUnit>()
.HasRequired(c => c.Company)
.WithMany(c => c.BusinessUnits)
.HasForeignKey(c => c.CompanyId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment