gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:03:09 25 4
gpt4 key购买 nike

我已经在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com