Ef Core 2 set value to ignored property on runtime

喜你入骨 提交于 2019-12-10 11:41:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!