首页 新闻 赞助 找找看

Entity FrameWork:Code First读取的时候无法将复键对应的实体映射出来?

0
悬赏园豆:20 [已解决问题] 解决于 2015-10-04 22:21

定义两个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();
            }

读取出来的结果如下

farcall的主页 farcall | 初学一级 | 园豆:186
提问于:2015-09-29 02:37
< >
分享
最佳答案
0

问题总结如下

http://www.cnblogs.com/farcall/p/4850342.html

farcall | 初学一级 |园豆:186 | 2015-10-04 22:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册