EF4.1(代码优先)-如何指定复合关系 [英] EF4.1 (code first) - How to specify a composite relationship

查看:119
本文介绍了EF4.1(代码优先)-如何指定复合关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linq to SQL中,我可以指定一个不必依赖于数据库中存在的外键和pk的关系,这对于创建这样的复合关系很有用:

In Linq to SQL I could specify a relationship that didn't have to depend on the foreign keys and pks existing in the database, useful for creating composite relationships like this:

public class Equipment_CableNormalised
{
    ...

    [Association(ThisKey = "EquipmentId,PortNumber", OtherKey = "EquipmentId,PortNumber", IsForeignKey = false)]
    public List<EquipmentPort> EquipmentPorts
    {
        get; set;
    }

}

然后生成类似于" .. join EquipmentPorts EP on EP.EquipmentId = blah and EP.PortNumber = Blah"的sql.

This then generated the sql similar to " .. join EquipmentPorts EP on EP.EquipmentId = blah and EP.PortNumber = Blah".

我可以在EF4.1中做同样的事情(使用注释或流畅的api)吗?我知道您可以指定复合键并使用[Keys]和[ForeignKeys]属性,但是这种关系不会映射到键...

Can I do the same sort of thing in EF4.1 (using annotations or fluent api)? I know you can specify composite keys and use the [Keys] and [ForeignKeys] attributes, but this relationship doesn't map to keys...

推荐答案

您的代码中的示例关系如何工作?我希望EquipementId一侧必须是PK或唯一密钥(L2S和EF均不支持),因为否则该关系将不存在(一对一和一对多要求唯一的主体).一旦在一侧成为PK,端口号即为冗余.

How does the sample relation from your code works? I expect that EquipementId must be either PK or unique key (not supported in both L2S and EF) on one side because otherwise the relation could not exist (both one-to-one and one-to-many demands unique principal). Once it is PK on one side the port number is redundant.

代码首先仅允许映射到键.如果您已有数据库,则可以在模型中作弊并以映射现有关系的方式映射新关系,但仍必须遵循简单的规则-主体中的属性是主键,从属实体中的属性被映射为外键

Code first allows only mapping to keys. If you have existing database you can cheat it in your model and map new relations in the same way as you would map existing but you still have to follow simple rule - properties in principal are primary keys, properties in dependent entity are mapped as foreign keys.

如果您希望EF为您生成数据库,那么您将始终在数据库中拥有所有关系.

If you want EF to generate DB for you, you will always have all relations in the database.

这篇关于EF4.1(代码优先)-如何指定复合关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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