Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Created December 29, 2015 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertoMonteiro/e4eb399baa18450fa3ff to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/e4eb399baa18450fa3ff to your computer and use it in GitHub Desktop.
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