c# - 不确定如何解决 'Unable to determine the principal end of an association' 错误

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

关于此错误的讨论有很多,我已经阅读了其中的 ~6 个。 (其中一些不适用,因为关系不是 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; }
}

但这让我犯了错误:

Unable to determine the principal end of an association between the types 'EZHomes.Data.Model.AccountSetting' and 'EZHomes.Data.Model.Account'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

如何指定Account作为委托(delegate)人?

谢谢!

最佳答案

我终于明白了。希望这会帮助别人。在非主表中:

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

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

关于c# - 不确定如何解决 'Unable to determine the principal end of an association' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601128/

相关文章:

c# - 从数组创建位图对象

c# - 尝试调用不存在的操作会创建一个永久请求

entity-framework - 我应该如何在 Entity Framework Code first 5.0 中将数据播种到多对多关系

c# - EF将重复记录添加到查找/引用表中

asp.net-mvc-4 - MVC4 模型属性应该是另一个类的列表或 ICollection

c# - 我可以避免对简单的 Linq to Entities 投影进行嵌套 SQL 查询吗?

c# - 使用 NativeWindow 显示任务栏项目

c# - .NET 中集合的内存分配

在 MVC 的 Global.asax 文件中使用 Application_PreRequestHandlerExecute 方法时,Jquery 和 css 在服务器上不起作用

asp.net-mvc - 神秘的 ASP.NET MVC Action 高延迟问题?