【问题标题】:Can't set the Relation between 2 DB Models无法设置 2 个数据库模型之间的关系
【发布时间】:2017-02-20 14:52:51
【问题描述】:

我遇到了这个问题:

我有这样的应用程序用户类

 
public class ApplicationUser : IdentityUser
    {
        public ROLES Role { get; set; }
        public int? CompanyId { get; set; }
        public int? AreaId { get; set; }
        public string Document { get; set; }
        public bool Enable { get; set; }

        [ForeignKey("CompanyId")]
        public virtual Company Company { get; set; }
        [ForeignKey("AreaId")]
        public virtual Area Area { get; set; }
        public virtual ICollection Measures { get; set; }

    }
 

我得到了另一个模型:

 

public class Area
    {
        public int AreaId { get; set; }
        public string AreaName { get; set; }
        public int CompanyId { get; set; }
        public string UserId { get; set; }

        [ForeignKey("CompanyId")]
        public virtual Company Company { get; set; }
        [Key, ForeignKey("UserId")]
        public ApplicationUser ApplicationUser { get; set; }
    }
 

当我尝试: 添加迁移

PM 控制台抛出:

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

我一直在尝试一整天,但我找不到一种方法来告诉实体框架识别关系。

有什么想法吗?

感谢阅读

【问题讨论】:

  • 我认为您的公司导航属性令人窒息。看起来它在 Area 类中是必需的。尝试在此处使用 Required 属性或使用 fluent API 来指定一个是必需的,另一个是可选的。

标签: entity-framework asp.net-mvc-5 ef-code-first entity-framework-migrations ef-code-first-mapping


【解决方案1】:

在Area类中为AreaId添加属性

[Key]
public int AreaId { get; set; }

如果您想要 ApplicationUser 和 Area 的 1-1 关系,请更新您的代码,例如

[Unique]
[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }

【讨论】:

  • 我想将 ApplicationUser 中的 AreaId 设置为可选键,并将 Application 用户设置为 Area 中的 OptionalKey。
  • 不...我想要一个 1-1 的可选关系。区域上的 ApplicationUser 是可选的,每个区域可以只有 1 个。 ApplicationUser 上的区域每个用户只能是 2 个。
  • 你能给我一个数据的例子吗
  • Okey 我想要这样的东西:ApplicationUser... Id= hf9d8fm-as9d(或类似的东西...)CompanyId = 9997654(但这也可以为空)(ForeignKey)AreaId = 665 (这也可以为空)(ForeignKey)Document = 10098264926 Enable = true 在另一边 AreaId 可以是:AreaId = 7789(PrimaryKey)AreaName = IT Deparment CompanyId = 88998752(这不能为空一个区域始终是一部分a Company) UserId = ajd9d7kas-djdj0as8sydh (这个是区域boss,也可以为null)
  • 按此顺序... ApplicationUsers 存储我所有不同公司和区域的用户 存储我不同公司的所有区域... 用户可以有一个区域或不可以有一个公司或不是。一个区域可以有一个老板区域,也可以没有,但总是有一个公司。
【解决方案2】:

The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations

这篇文章给了我我需要的答案!!! 好难找……

所以我把帖子放在这里... 感谢您的所有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2020-10-12
    • 2021-06-13
    相关资源
    最近更新 更多