问题
I have an entity with boolean property named "ReadOnly", the value of this property depends on which user is using the application.
In the DbContext i configured the property to be ignored.
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().Ignore(e => e.ReadOnly);
}
}
How can i set the correct value calculated on runtime so that i haven't to remind to calculate the property everytime?
EDIT: I was thinking something like
int loggedUserId = HttpSession.UserId;
modelBuilder.Entity<Entity>().Property(e => e.ReadOnly).Value = loggedUserId > 5;
This way i have always the correct value based on User logged to the application.
回答1:
You can try using a filter, but I'm not sure it will work since you need to set the property per request. Your best bet is just to make a method on the class that accepts the user and returns the calculated value. Something like this:
bool IsReadOnly(int userId){
return userId > 5;
}
回答2:
I found out that AutoMapper has ProjectTo function that does what i need, ProjectTo will tell AutoMapper’s mapping engine to emit a select clause to the IQueryable
Example of my configuration:
configuration.CreateMap(typeof(Entity), typeof(Entity))
.ForMember(nameof(Entity.IsReadOnly), opt.MapFrom(src => currentUserResolver.GetUserId() > 5));
Usage:
myDbSet.AsQueryable().ProjectTo<TEntity>();
http://docs.automapper.org/en/stable/Queryable-Extensions.html
来源:https://stackoverflow.com/questions/50627668/ef-core-2-set-value-to-ignored-property-on-runtime