无法确定关联的主要端 - 实体框架模型优先

Mic*_*hal 13 c# entity-framework fluent-interface

我在Visual Studio中创建了实体数据模型.现在我有一个SQL查询文件和从Model生成的C#类.

题:

生成的类没有注释或代码(Fluent API).可以吗?我试图运行我的应用程序但抛出了异常:

无法确定类型"Runnection.Models.Address"和"Runnection.Models.User"之间关联的主要结尾.必须使用关系流畅API或数据注释显式配置此关联的主要结尾.

我读到我不能将Fluent API与"Model First"一起使用.那我该怎么办?

码:

用户

public partial class User
{
    public User()
    {
        this.Events = new HashSet<Event>();
        this.CreatedEvents = new HashSet<Event>();
    }

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Photo { get; set; }
    public int EventId { get; set; }
    public string Nickname { get; set; }
    public OwnerType OwnerType { get; set; }
    public NetworkPlaceType PlaceType { get; set; }

    public virtual ICollection<Event> Events { get; set; }
    public virtual Address Address { get; set; }
    public virtual ICollection<Event> CreatedEvents { get; set; }
    public virtual Owner Owner { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

地址

public partial class Address
{
    public int Id { get; set; }
    public string Street { get; set; }
    public string StreetNumber { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }

    public virtual User User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

上下文

// Model First不使用此方法

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Address>().HasRequired(address => address.User)
                                   .WithRequiredDependent();
        modelBuilder.Entity<User>().HasRequired(user => user.Address)
                                   .WithRequiredPrincipal();

        base.OnModelCreating(modelBuilder);
    }
Run Code Online (Sandbox Code Playgroud)

Eri*_* W. 29

您必须以一对一的关系指定主体.

public partial class Address
{
    [Key, ForeignKey("User")]
    public int Id { get; set; }
    public string Street { get; set; }
    public string StreetNumber { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public string Country { get; set; }

    public virtual User User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

通过指定FK约束,EF知道用户必须首先存在(主体)并且地址跟随.

进一步阅读MSDN.

另外,请看这个SO答案.


从评论更新


在设计器中,选择关联(用户和地址之间的行).在属性窗口中,单击"参照约束"上的[...]按钮(或双击该行).将Principal设置为User.