【问题标题】:Entity Framework Two foreign keys as primary keyEntity Framework 两个外键作为主键
【发布时间】:2013-03-06 06:52:54
【问题描述】:

所以我正在使用实体代码,并且我有一个看起来像这样的用户类:

public class User
    {
        [Key]
        public string Username { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime LastModified { get; set; }
    }

我正在尝试制作“朋友表”,无论我想出什么,我都会在创建数据库时遇到错误。这是我目前在 Friends Class 中的内容:

public class Friend
    {
        [Key, ForeignKey("User")]
        public virtual User MyUser { get; set; }

        [Key,ForeignKey("User")]
        public virtual User MyFriend { get; set; }

        public bool IsAccepted { get; set; }
    }

这是我得到的错误:

类型“Core.Model.Friend”的属性“MyUser”上的 ForeignKeyAttribute 无效。在依赖类型“Core.Model.Friend”上找不到外键名称“用户”。 Name 值应该是一个逗号分隔的外键属性名称列表。

我错过了什么?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您需要使用Column 属性。通常我会使用这样的东西:

    public class Friend
    {
        [Key]
        [Column(Order = 0)]
        public int MyUserId { get; set; }
    
        [Key]
        [Column(Order = 1)]
        public int MyFriendId { get; set; }
    
        [ForeignKey("MyUserId")]
        public virtual User MyUser { get; set; }
    
        [ForeignKey("FriendId")]
        public virtual User MyFriend { get; set; }
    
        public bool IsAccepted { get; set; }
    }
    

    我不确定如果将Column 属性直接映射到导航属性会发生什么。如果您愿意,可以尝试一下,看看会发生什么。但上述方法通常对我有用。

    或者,如果您更改为使用流畅的映射,您可以执行以下操作:

    HasKey(u => new { u.MyUserId , u.MyFriendId });
    

    【讨论】:

    • 我尝试了上面的代码,但我将整数更改为字符串,因为我的用户类键是一个字符串。当我这样做时,我现在从数据库中得到一个循环引用错误。
    • 这帮助我修复了一个可怕的“找不到 Table_ID 列”错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2012-06-29
    • 2023-04-05
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多