Reputation:
How do I map two class members to one column in Entity Framework database? Is it possible? I tried the following code and received errors
modelBuilder.Entity<Product>(entity =>
{
entity.Property(e => e.Id)
.HasColumnName("ProductId");
entity.Property(e => e.ProductId)
.HasColumnName("ProductId");
Error Run Time:
'Product.Id' and 'Product.ProductId' are both mapped to column 'ProductId' in 'Product' but are configured with different value generation strategies.'
We are trying to resolve this issue, otherwise the generic repository will have to use Expression Builders
Net Core: Generic Repository Primary Id Key Performance in Entity Framework
Their top solution was not working.
var idName = _context.Model.FindEntityType(typeof(TEntity))
.FindPrimaryKey().Properties.Single().Name;
Upvotes: 3
Views: 3326
Reputation: 34968
Generic repositories are an anti-pattern with Entity Framework. They're honestly not worth the hassle.
However, to map a ProductID column in the entity:
entity.Property(e => e.Id)
.HasColumnName("ProductId");
entity.Ignore(e => e.ProductId);
The catch here is that when you're writing your Linq expressions that would go through EF to SQL you need to avoid using any ignored properties.
Alternatively I'd suggest removing the ProductId field in the entity and simply relabel the field in your view models & DTOs that front-end code and any serializer uses, setting up Automapper to translate the ID column.
Upvotes: 4