3

我有一个旧数据库,它有两个列,我想将它们映射为 1 个 ID,这可能吗

例如

    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 + UserName ...因为这两个列共享一个唯一的键约束...

不知道这是否有意义,但任何建议都会很棒......请不要询问数据库设计=>这就像它一样,不应该改变......这就是为什么我认为 EF 代码优先可以帮助我(希望交叉手指)......因为看起来数据库没有定义 pk 只是唯一的键约束......

无论如何...帮助会很棒..

4

2 回答 2

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;} 
}

然后使用 Fluent 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...。

这是有关复杂类型的更多信息。

于 2011-04-16T01:09:49.457 回答
0

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

于 2010-08-04T16:09:35.587 回答