【发布时间】:2015-01-25 14:13:05
【问题描述】:
为我有两个客户和用户表的情况编写模型。每个用户记录可能有一个可选的相关客户记录,反之亦然,但它们都不是必须的。我发现FK Associations 不是我需要的,但Independent Associations 是。但我只能找到一种让它工作的方法,我不断收到“无法确定主体端......这个关联的主体端必须使用关系流式 API 或数据注释显式配置。”例外。
我的模型很简单:
public class User
{
[Key]
public int Id { get; set; }
[StringLength(20)]
public string CustomerId { get; set; }
public string Password { get; set; }
public bool Locked { get; set; }
//[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
public class Customer
{
[Key]
[Column("Id", TypeName = "nvarchar")]
[StringLength(20)]
public string Id { get; set; } // nvarchar 20
[Required]
public string GivenName { get; set; } // nvarchar 100
[Required]
public string Surname { get; set; } // nvarchar 100
//[InverseProperty("Customer")]
public virtual User User { get; set; }
}
我尝试添加 ForeignKeyAttribute 和 InversePropertyAttribute,它们目前已被注释掉,但它们也没有帮助。如果可能的话,我更喜欢使用数据注释而不是流畅的 API。
【问题讨论】:
-
你想依赖延迟加载,对吗?你看过这篇文章吗:stackoverflow.com/questions/12606948/…
-
@DDiVita 是的,延迟加载,是的,我已经看到了这个问题,但是问题是 Principal 有一个
RequiredAttribute,在我的情况下,用户记录可以在没有客户记录的情况下存在。 -
@DDiVita 我已经尝试使用
RequiredAttribute,正如答案所暗示的那样,但EF找不到Customer_ID,然后我添加了ForeignKeyAttribute并收到了这个异常:\tSystem.Data.Entity .Edm.EdmAssociationEnd: : 多重性在关系“User_Customer”中的角色“User_Customer_Source”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是“*”。
标签: c# asp.net-mvc entity-framework ef-code-first data-annotations