首先是EF代码 – 复合键

我有一个遗留数据库有两个列,我想将它们映射为1 ID这是可能的

例如

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

然后我的Modelbinder看起来像这样

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

我需要的是像映射中的ProductID = ShortDescription + UserName ……因为这两个列共享一个独特的键约束…

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

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

听起来你想要一个复杂的类型并希望通过使用在属性名称末尾附加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() .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() .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 ….

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

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