c# - 无法确定关联的主要端 - Entity Framework 模型优先

标签 c# entity-framework fluent-interface

我已经在 Visual Studio 中创建了实体数据模型。现在我有了包含从模型生成的 SQL 查询和 C# 类的文件。

问题:

类是在没有注释或隐藏代码的情况下生成的 (Fluent API)。可以吗?我尝试运行我的应用程序但抛出了异常:

无法确定类型“Runnection.Models.Address”和“Runnection.Models.User”之间关联的主体端。该关联的主体端必须使用关系流畅的 API 或数据注释进行显式配置。

我读到我不能将 Fluent API 与“模型优先”一起使用。那我该怎么办?

代码:

用户

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; }
}

地址

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; }
}

上下文

//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);
    }

最佳答案

您必须在一对一关系中指定委托(delegate)人。

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; }
}

通过指定 FK 约束,EF 知道用户必须首先存在(主体),然后是地址。

Further reading at MSDN.

Also, see this SO answer.


根据评论更新


在设计器中,选择关联(用户和地址之间的线)。在属性窗口中,点击 Referential Constraint 上带有 [...] 的按钮(或双击该行)。将委托(delegate)人设置为用户。


关于c# - 无法确定关联的主要端 - Entity Framework 模型优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505201/

相关文章:

c# - Entity Framework 不适用于存储过程!

api - CaSTLe Windsor Fluent Registration - Pick() 有什么作用?

c# - Fluent API 中的快捷方式可根据需要设置多个属性

c# - AutoMapper:ForMember() 和 ForPath() 有什么区别?

c# - 委托(delegate)与暴露属性

c# - EF Core 中已修改实体的自有类型属性不持久

c# - 没有通用扩展方法的类型推断

c# - 使用 asp.net mvc 应用程序的 HttpClient post 请求 WebApi

c# - 我的列表 <> 返回找到的文件的确切数量,但在整个循环中显示相同的数据

c# - Entity Framework 外键关系不返回任何数据