如何首先在 Entity Framework 4 代码中映射复合主键? [英] How do I map a composite primary key in Entity Framework 4 code first?

查看:28
本文介绍了如何首先在 Entity Framework 4 代码中映射复合主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要掌握 EF4 代码,到目前为止我很喜欢它.但是我无法将实体映射到具有复合主键的表.

I'm getting to grips with EF4 code first, and liking it so far. But I'm having trouble mapping an entity to a table with a composite primary key.

我尝试过的配置如下:

public SubscriptionUserConfiguration()

    {
                Property(u => u.SubscriptionID).IsIdentity();
                Property(u => u.UserName).IsIdentity();
    }

抛出这个异常:无法推断实体类型订阅用户"的键.

Which throws this exception: Unable to infer a key for entity type 'SubscriptionUser'.

我错过了什么?

推荐答案

你也可以使用

HasKey(u => new { u.SubscriptionID, u.UserName });

我发现的一个限制是以下方法不起作用:

One limitation I have found is that the following do not work:

public ProjectAssignmentConfiguration()
{
    HasKey(u => u.Employee.EmployeeId);
    HasKey(u => u.Project.ProjectId);
}

public ProjectAssignmentConfiguration()
{
    HasKey(u => new { u.Employee.EmployeeId, u.Project.ProjectId });
}

那么如何设置一个实体,其中连接表有一个由外键组成的主键?

So how do you set up an entity where the join table has a primary key that is composed of foreign keys?

这篇关于如何首先在 Entity Framework 4 代码中映射复合主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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