The first EF code is a composite key

I have an outdated database with two columns and I want to display them as 1 ID, this is possible

eg

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

then my Modelbinder looks like this

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

I would need something like ProductID = ShortDescription + UserName in the mapping ... because these two columns have a unique key limit ...

I don’t know if this is so, but any suggestions would be great ... Please do not ask about the design of the database => it looks like it should not be changed ... why did I think that the EF code could help first me (hopefully cross your fingers) ... because it looks like db doesn't have pk defined only by unique key constraints ...

anyway ... help would be awesome.

+3
2

, . , , .

EF CF .

EF CF Key FluentAPI.

:

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

Fluent 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....

.

+11

, . , , .

. , . EF , ?

, .

0

Source: https://habr.com/ru/post/1757853/


All Articles