Created
December 29, 2015 12:43
-
-
Save AlbertoMonteiro/e4eb399baa18450fa3ff to your computer and use it in GitHub Desktop.
Stackoverflow Question http://stackoverflow.com/questions/34509747/entity-framework-6-hasrequired-and-withmany-partially-working-not-working
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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