Ef Core 2 在运行时将值设置为忽略的属性 [英] Ef Core 2 set value to ignored property on runtime
问题描述
我有一个名为ReadOnly"的布尔属性的实体,该属性的值取决于使用该应用程序的用户.
I have an entity with boolean property named "ReadOnly", the value of this property depends on which user is using the application.
在 DbContext 中,我配置了要忽略的属性.
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?
我在想像
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.
推荐答案
我发现 AutoMapper 有 ProjectTo 函数可以满足我的需要,ProjectTo 会告诉 AutoMapper 的映射引擎向 IQueryable 发出一个 select 子句
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
我的配置示例:
configuration.CreateMap(typeof(Entity), typeof(Entity))
.ForMember(nameof(Entity.IsReadOnly), opt.MapFrom(src => currentUserResolver.GetUserId() > 5));
用法:
myDbSet.AsQueryable().ProjectTo<TEntity>();
http://docs.automapper.org/en/stable/Queryable-Extensions.html
这篇关于Ef Core 2 在运行时将值设置为忽略的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!