实体框架两个外键作为主键 [英] Entity Framework Two foreign keys as primary key

查看:417
本文介绍了实体框架两个外键作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用实体代码firest,我有一个用户类,如下所示:

So i am working with entity code firest and i have a user class that looks like this:

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

我正在努力做一个朋友表,无论我想到我在数据库创建时遇到错误。这是我目前在朋友类中的:

I am trying to make a "friends table" and no matter what i come up with I get an error on the db creation. This is what I Currently have in the 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中找不到外键名User。名称值应该是以逗号分隔的外键属性名称列表。

The ForeignKeyAttribute on property 'MyUser' on type 'Core.Model.Friend' is not valid. The foreign key name 'User' was not found on the dependent type 'Core.Model.Friend'. The Name value should be a comma separated list of foreign key property names.

我缺少什么?

推荐答案

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

You need to use the Column attribute. Normally I would use something like this:

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; }
}

我不知道如果您映射属性直接指向导航属性。你可以尝试一下,如果你喜欢看看会发生什么..但是上面一般适用于我。

I'm not sure what would happen if you map the Column attribute directly to the navigation property. You can try it if you like and see what happens.. but the above generally works for me.

或者,如果你改变使用流畅的绘图,你可以做一些事情像这样:

Alternatively, if you change to use fluent mapping, you can do something like this:

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

这篇关于实体框架两个外键作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆