2010-08-03 47 views
3

我有两个collumns旧的数据库,我想将它们映射为1点的ID是可能EF代码第一 - 复合键

例如

public class Product 
{ 
public string ProductID {get;set;} 
public string ShortDescription {get;set;} 
public string UserName {get;set;} 
} 

然后我ModelBinder的看起来像这样

modelBinder.Entity<Product>(). 
HasKey(p=>p.ProductID) 
.MapSingle(product => 
new { 
colShotDesc = product.ShortDescription, 
colUser = product.UserName 
} 
).ToTable("Products"); 

我需要什么会像在映射 的ProductID = SHORTDESCRIPTION +用户名... 因为这两个collumns共享的uniq ue key contraint ...

不知道这是否使得sens,但任何建议将是伟大的... 请不要问关于数据库设计=>这是这样的,不应该改变。这就是为什么我认为EF代码优先可以帮助我(希望交叉手指)... ,因为它看起来像分贝没有得到PK定义只是唯一的关键限制...

无论如何... 帮助将是了不起的..

回答

0

实际上,你想映射一个概念属性到几个存储列。 有一个代码将列中的值连接到属性,到目前为止非常好。
但让我们想象一下向上下文添加新实体的过程。 因此,我们为该物业设定了价值。 EF应该如何知道将该属性的值写入两列的规则?
不确定这种情况是否可能实现。

+0

是的我同意它不是那么干净,但这是我正在面对的分贝。由于这两列在数据库级别上有一个唯一的约束,因此应该设置它们。我也使用验证来确保它们已被设置。 我希望我的解决方案在代码中更清晰,因此我正在查找复合产品ID。我如何在代码优先的情况下组装我的连接字段? – 2010-08-05 08:12:02

11

听起来就像你想要一个复杂的类型,并希望通过在属性名称的末尾使用附加ID的约定将复杂类型识别为键。

EF CF此时无法做到这一点。

您可以通过Key属性或FluentAPI告诉EF CF有关组合键的信息。

数据注释:

public class Product 
{ 
    [Key, Column(Order=0)] 
    public string ShortDescription {get;set;} 
    [Key, Column(Order=1)] 
    public string UserName {get;set;} 
} 

流利的API:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Product>() 
       .HasKey(p=> new{p.ShortDescription, p.UserName}); 
} 

您可以创建一个复杂的类型,你可以在你的代码中使用的工作越多,你希望你的代码在概念上的工作方式。

public class Product 
{ 
    public ProductID Key {get;set;} 
} 

public class ProductID 
{ 
    public string ShortDescription {get;set;} 
    public string UserName {get;set;} 
} 

然后用流利的API映射它:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.ComplexType<ProductID>() 
       .Property(p=>p.ShortDescription) 
       .HasColumnName("ShortDescription") 
       .Property(p=>p.UserName) 
       .HasColumnName("UserName"); 
} 

或者,如果你想使用数据注释:

[ComplexType] 
public class ProductID 
{ 
    [Column("ShortDescription")] 
    public string ShortDescription {get;set;} 
    [Column("UserName")] 
    public string UserName {get;set;} 
} 

您必须指定列名或配置将假定列名是ProductID_ShortDescription ....

Here's some more info on Complex Types.