ser*_*nfo 3 c# entity-framework code-first
我有一个遗留数据库有两个列,我想将它们映射为1 ID这是可能的
例如
public class Product
{
public string ProductID {get;set;}
public string ShortDescription {get;set;}
public string UserName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后我的Modelbinder看起来像这样
modelBinder.Entity<Product>().
HasKey(p=>p.ProductID)
.MapSingle(product =>
new {
colShotDesc = product.ShortDescription,
colUser = product.UserName
}
).ToTable("Products");
Run Code Online (Sandbox Code Playgroud)
我需要的是像映射中的ProductID = ShortDescription + UserName ...因为这两个列共享一个独特的键约束...
不知道这是否有意义,但任何建议都会很棒...请不要问数据库设计=>这就像它是,不应该改变...这就是为什么我认为EF代码优先帮助我(希望交叉手指)...因为它看起来像db没有定义pk只是唯一的键约束...
无论如何......帮助会很棒..
Kev*_*che 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;}
}
Run Code Online (Sandbox Code Playgroud)
流畅的API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasKey(p=> new{p.ShortDescription, p.UserName});
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个可以在代码中使用的复杂类型,以便更好地按照您希望代码在概念上工作的方式工作.
public class Product
{
public ProductID Key {get;set;}
}
public class ProductID
{
public string ShortDescription {get;set;}
public string UserName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
然后使用Fluent API映射它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ComplexType<ProductID>()
.Property(p=>p.ShortDescription)
.HasColumnName("ShortDescription")
.Property(p=>p.UserName)
.HasColumnName("UserName");
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要使用数据注释:
[ComplexType]
public class ProductID
{
[Column("ShortDescription")]
public string ShortDescription {get;set;}
[Column("UserName")]
public string UserName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
您必须指定列名称,否则配置将假定列名称为ProductID_ShortDescription ....
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |