开发者

Entity Framework 4 CTP 4 Code First: how to work with unconventional primary and foreign key names

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 "f开发者_开发知识库kAddressWork".

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.

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.

Update

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.


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-code-first.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜