【问题标题】:Not sure how to get around 'Unable to determine the principal end of an association' error不确定如何解决“无法确定关联的主体端”错误
【发布时间】:2017-01-11 21:36:51
【问题描述】:

关于这个错误有很多线程,我已经阅读了大约半打。 (其中一些不适用,因为关系不是 1:1。)我尝试了一些方法,但仍然出现错误。

我有两张桌子,AccountAccountSettings。他们有 1:1 的关系。但是,Account 是主要的。它可以在没有AccountSettings 的情况下存在,但反过来不行。

这就是我原来的样子……

public class Account
{
    [Key]
    public int AccountID { get; set; }
    public int? AccountSettingID { get; set; }

    [ForeignKey("AccountSettingID ")]
    public virtual AccountSetting AccountSetting { get; set; }
}

然后……

public class AccountSetting 
{
    [Key]
    public int AccountSettingID { get; set; }
    public int AccountID { get; set; }

    [ForeignKey("AccountID ")]
    public virtual Account Account { get; set; }
}

但这让我犯了错误:

无法确定类型“EZHomes.Data.Model.AccountSetting”和“EZHomes.Data.Model.Account”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。

如何指定Account为原则?

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc ef-code-first code-first


    【解决方案1】:

    我终于明白了。希望这会对其他人有所帮助。在非主表中:

    public class AccountSetting 
    {
        [Key]
        public int AccountSettingID { get; set; }
        [Required]
        public int AccountID { get; set; }
    
        [Required, ForeignKey("AccountID ")]
        public virtual Account Account { get; set; }
    }
    

    【讨论】:

    • Account 表/实体不需要将 AccountSettingId 作为外键 - 当您添加 AccountSetting 并设置 AccountId 时会创建关系。
    • 所以我添加它的原因是因为我希望能够从Account导航到AccountSettings。如果没有将 AccountSettingId 作为外键的 Account 表,这可能吗?
    • 是的,有很多方法取决于您如何为延迟加载、代理创建、使用“包含/加载”等配置 EF。但您通常会像这样访问数据:Account.AccountSetting。当从数据库中检索数据并通过外键提供双向导航时,EF 通常会将 AccountySetting 设置为 Account 实体的子对象/实体。
    • 好的,谢谢。我认为只有指定外键才能从一个表导航到另一个表。
    猜你喜欢
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多