简体   繁体   English

EF 4.1双向一对一问题

[英]EF 4.1 Bidirectional one-to-one problem

Hi I am having a problem with a simple EF 4.1 code first model. 嗨,我有一个简单的EF 4.1代码第一模型的问题。

I have a class person and a class survey that are bidirectionally linked. 我有一个双向联系的班级人员和班级调查。 The database model is correct but I always get this error: 数据库模型是正确的但我总是得到这个错误:

Unable to determine the principal end of an association between the types 'DAL.Models.Survey' and 'DAL.Models.Person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Class Person 班级人员

[Key]
        public Guid Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string Email { get; set; }

        public virtual Survey Survey { get; set; }

Class Survey 班级调查

   [Key]
        public Guid Id { get; set; }

        public bool IsFinished { get; set; }

        public virtual Person Person { get; set; }

Datacontext: 的DataContext:

 modelBuilder.Entity<Survey>().HasRequired(s => s.Person).WithOptional().WillCascadeOnDelete(true);

Can anyone help please 任何人都可以帮忙

You should define the other navigation property in your mapping since you have it in the model. 您应该在映射中定义其他导航属性,因为您在模型中具有该属性。 Otherwise EF will create a second (one-to-many) association: 否则EF将创建第二个(一对多)关联:

modelBuilder.Entity<Survey>()
            .HasRequired(s => s.Person)
            .WithOptional(p => p.Survey)
            .WillCascadeOnDelete(true);

I think you have to specify either a foreign key property through HasForeignKey or foreign key column name using Map. 我认为你必须通过HasForeignKey指定一个外键属性或使用Map指定外键列名。 Something like this: 像这样的东西:

modelBuilder.Entity<Survey>()
    .HasRequired(s => s.Person)
    .WithOptional()
    .WillCascadeOnDelete(true)
    .Map(m => m.MapKey("fk_column"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM