实体框架4 CTP 4 code第一:如何与非常规的主键和外键名工作与非、实体、主键、常规

2023-09-03 22:59:33 作者:任你风情万种我只视她如命

有没有在实体框架4的方式(使用CTP4和code首先,如果该事项)更改用于自动识别主键和外键的约定?我试图用EF与使用PK / FKpreFIX,而不是一个id后缀,以纪念钥匙遗留数据库。此外,它并不少见有多个外键,一个地址表,例如,被称为fkAddressHome和fkAddressWork。

Is there a way in Entity Framework 4 (using CTP4 and Code First if that matters) to change the conventions used to automatically identify primary and foreign keys? I'm trying to use EF with a legacy database that uses a "pk/fk" prefix rather than an "id" suffix to mark keys. Also, it's not uncommon to have multiple foreign keys to an Address table, for example, called "fkAddressHome" and "fkAddressWork".

我会preFER改变以系统的方式这种行为的方法,这样我就不必指定这些变化对每个表。我看着在OnModelCreating方法覆盖列名的选项,但它是令人失望地看到,如果添加一列的方式,那么你必须添加所有。而这违反了我干枯的情感。

I would prefer a method for changing this behavior in a systematic way so that I don't have to specify these changes for every table. I looked into the option of overriding the column names in the OnModelCreating method, but it was disappointing to see that if you add one column that way, then you have to add them all. And that violated my DRY sensibilities.

然而,任何解决方案将是AP preciated。 EF4,特别是CTP4的code首先增强,真的,真的很好。我期待着看到什么令到EF的下一个版本。感谢您的帮助。

However, any solution would be appreciated. EF4, and particularly CTP4's Code First enhancements, are really, really nice. I look forward to seeing what else makes into the next version of EF. Thanks for the help.

我能够映射加入下面我OnModelCreating法的关系:

I was able to map the relationship by adding the following to my OnModelCreating method:

modelBuilder.Entity<User>()
    .HasRequired<Address>(p => p.Address)
    .HasConstraint((p, u) => p.fkAddressHome == u.pkAddress);

我不知道这是最优雅的方式,或者这将最终导致我任何问题,但它的工作现在。

I'm not sure if that's the most elegant approach, or if this will ultimately cause me any problems, but it's working for now.

推荐答案

与模型构建器流利的接口是一个正确的方式来做到这一点。 您还可以使用DataAnnotation属性(如果你preFER属性):

Fluent interface with Model Builder is a proper way to do that. You can also use DataAnnotation attributes (if you prefer attributes):

http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-$c$c-first.aspx