将属性映射到实体框架 CTP5 中的(不同名称的)外键字段
我正在尝试使用实体框架 CTP5 Fluent API 来映射现有数据库。我有以下课程:
public class Shop
{
public long Id
{
get;
set;
}
}
public class Sale
{
public long Id
{
get;
set;
}
public virtual Shop Shop
{
get;
set;
}
}
相应的表称为“商店”和“销售”。 Sales 有一个 StoreId 外键,指向 Stores 表中的 Id 字段。
我正在努力将 Sale.Shop.Id 映射到表中的 StoreId 。我不能随意将其更改为 ShopId,因此需要映射它。
在 CTP4 中,我使用:
modelBuilder.Entity<Sale>().MapSingleType(x =>
new
{
Id = x.Id,
StoreId = x.Shop.Id
});
我尝试了以下操作:
modelBuilder.Entity<Sale>().Property(x => x.Shop.Id).HasColumnName("StoreId");
但是,这似乎仅适用于原始类型。
我如何指定这个映射?
I'm trying to use the Entity Framework CTP5 Fluent API to map an exist database. I have the following classes:
public class Shop
{
public long Id
{
get;
set;
}
}
public class Sale
{
public long Id
{
get;
set;
}
public virtual Shop Shop
{
get;
set;
}
}
The corresponding tables are called "Stores" and "Sales". Sales has a StoreId foreign key that points to the Id field in the Stores table.
I'm struggling to map the Sale.Shop.Id to the StoreId in the table. I'm not at liberty to change it to ShopId, so need to map it.
In CTP4, I was using:
modelBuilder.Entity<Sale>().MapSingleType(x =>
new
{
Id = x.Id,
StoreId = x.Shop.Id
});
I tried the following:
modelBuilder.Entity<Sale>().Property(x => x.Shop.Id).HasColumnName("StoreId");
However, it seems this only works with a primitive type.
How do I specify this mapping?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:我在下面添加了 EF 4.1 候选发布版的修订版本
经过一番搜寻,我找到了适合我的答案:
EF4.1 RC 版本:
在您的情况下:
我的版本略有不同,因为我有关系双方的导航属性。
Update: I've added a revised version for the Release Candidate of EF 4.1 below
After some hunting, I've found the answer that works for me:
EF4.1 RC version:
in your case:
My version is slightly different because I have navigation properties on both sides of the relationship.
我认为解决此问题的最佳方法是将您的独立关联升级为外键关联,这意味着不要隐藏外键
ShopId
,实际上将其包含在Sale
类中。然后,您可以使用 Data Aannotations/Fluent API 更改其列名称以匹配您现有的架构:其结果是所需的数据库模式:
I think the best way to solve this would be to upgrade your independent Association to be a Foreign Key Association meaning that instead of hiding the foreign key
ShopId
, actually including it inSale
class. Then you can use Data Aannotations/Fluent API to change its column name to match to your existing schema:Which results to the desired DB Schema:
我认为您正在寻找的是
RelatedTo
属性。更多信息请参见 这篇 ADO.NET 团队博客文章。I think what you're looking for is the
RelatedTo
attribute. More information in this ADO.NET team blog post.