c# - EF code first - composite key -
I have a legacy database that has two columns and I want to map them because 1 ID is possible
For example
public class product {public string ProductID {get; Set;} public string short-description {get; Set;} public string username {get; Set;}}
Then my modelbrander looks like this
Modelbinder Anti & lt; Products & gt; () HasKey (P = & gt; p.ProductID) .MapSingle (Product => New {colShotDesc = product.ShortDescription, colUser = product.UserName}) .ToTable ("Product");
I would like something like ProductID = ShortDescription + UserName in the mapping ... because these two columns are part of a unique key mating ...
don 't Know that this makes sense but no suggestion would be great ... please do not ask about database design => this is it and it should not be changed ... so I thought EF code can help me first (Hopefully cross fingers) ... because it seems that PK Unique key constraints have not been defined ...
Anyway ... help will be awesome ..
It looks as if you want a complex type and want to identify the complex type as the key so that the conference can be used to attach the ID to the end of the property name
EF CF can not do this at this time.
You can tell EF CF about a composite key through key attribute or FluentAPI
data annotation.
public class product {{key, column (command = 0)} public string shortDescription {find; Set;} [key, column (command = 1)] get public string username { Set;}}
Fluent API:
Protected Override Zero OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.Entity & LT; Products & gt; () .HasKey (P => New {p.ShortDescription, p.UserName}); }
You can create a complex type that you can use in your code to do as much as possible in your code. Product {public product ID key {receipt; Set;}} public class ProductID {public string short-description {get; Set;} public string username {get; Set;}}
Then use the well-known API to map it:
protected override zero OnModelCreating (modelBuilder modelBuilder) {modelBuilder.ComplexType & LT; ProductID & gt; () .Property (P = & gt; p.ShortDescription) .HasColumnName ("ShortDescription"). Property (P = & gt; Page Username) .HasColumnName ("Username"); } You want to use data annotation: [complexType] public class ProductID {[Column ("ShortDescription")] Public String ShortDescription { get receive; Set;} [column ("user name")] public string username {get; Set;}}
You must specify the column name or the name of the configuration column is the ProductID_ShortDescription ....
Comments
Post a Comment