定义两个one to many 关系的实体
public class Department { public Department( ) { Persons = new HashSet<Person>(); } [Key] public int DepartmentId { get; set; } public string Name { get; set; } public ICollection<Person> Persons { get; set; } } public class Person { public Person( ) { Department = new Department(); } [Key] public int PersonId { get; set; } public string Name { get; set; } public int DepartmentId { get; set; } [ForeignKey("DepartmentId")] public virtual Department Department { get; set; } }
数据库上下文
public class AllContent:DbContext { public AllContent( ):base("testData") { Database.SetInitializer<AllContent>(null); } public DbSet<Person> Persons { get; set; } public DbSet<Department> Departments { get; set; } }
操作/增加-->可以正常写入
using (var db = new AllContent()) { Person person = new Person(); person.Name = "小王"; person.Department.Name = "行政"; db.Persons.Add(person); db.SaveChanges(); }
读取为何不能成功,问题出在哪里呢?
using (AllContent db = new AllContent()) { Person person = db.Persons.Include(p => p.Department).FirstOrDefault(); }
读取出来的结果如下
问题总结如下
http://www.cnblogs.com/farcall/p/4850342.html