【问题标题】:EF -- Unable to determine the principal end of an association between the typesEF -- 无法确定类型之间关联的主体端
【发布时间】:2015-01-25 00:57:23
【问题描述】:

我无法弄清楚我在这里做错了什么。我正在使用 asp.net Identity,并创建了一个名为 Person 的新实体。我更新了ApplicationUser 类以引用Person。我想创建一个从PersonUser 的导航属性。但是当我执行更新数据库时,我不断收到一条错误消息

无法确定类型“myapp.Models.ApplicationUser”和“myapp.Models.DataModels.Person”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。

public class Person 
{
    public Guid ID {get; set;}
    ...
    public virtual ApplicationUser user {get; set;}
}

public class ApplicationUser
{
    ...
    public Person person {get; set;}
}

在代码中,我正在执行以下操作

ApplicationUser user = new ApplicationUser {...} 

Person person = new Person {....} 
user.person = person;

我也想知道是否需要为Person 的虚拟属性设置任何内容,例如person.user = user

我已尝试通过对虚拟财产执行以下操作来关注此Unable to determine the principal end of an association between the types

public class Person 
{
    public Guid ID {get; set;}
    ...
    [ForeignKey("ID")]        
    public virtual ApplicationUser user {get; set;}
}

谢谢

【问题讨论】:

    标签: c# asp.net-mvc entity-framework entity-framework-6


    【解决方案1】:

    1:1 关系中,一端必须是主体,而另一端必须是从属Principal end 是将插入第一个并且可以在没有依赖的情况下存在从属端是必须插入在主体之后的端,因为它具有到主体的外键。在这里,您需要将[Required] 属性添加到 principal 属性并从模型中删除 [ForeignKey("ID")]

    您还在模型中结合了延迟加载Virtual 属性)和急切加载功能。

    【讨论】:

    • 嗨,Amir,我应该放置哪一个所需的属性 - 它应该放在 ApplicationUser.Person 还是 Person.User 中?我假设它应该在 ApplicationUser.Person 中,但我在 Person.User 上尝试过,我能够执行 Update-Database。但我原以为会首先创建 ApplicationUser 实体。
    • @user3836415 依赖哪一个?为其导航属性添加[Required] 属性。
    • 我尝试将 [required] 注释添加到每个注释并每次编译它,我得到相同的结果。
    • 我也发现Id属性和reference属性都必须添加[Required] attr
    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2014-08-14
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多