Ef Core 2 在运行时将值设置为忽略 属性
Ef Core 2 set value to ignored property on runtime
我有一个布尔值 属性 的实体,名为 "ReadOnly",这个 属性 的值取决于哪个用户正在使用该应用程序。
在 DbContext 中,我将 属性 配置为忽略。
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().Ignore(e => e.ReadOnly);
}
}
如何设置运行时计算的正确值,这样我就不用每次都提醒计算 属性?
编辑:我在想
int loggedUserId = HttpSession.UserId;
modelBuilder.Entity<Entity>().Property(e => e.ReadOnly).Value = loggedUserId > 5;
通过这种方式,我始终可以根据登录到应用程序的用户获得正确的值。
您可以尝试使用 filter,但我不确定它是否有效,因为您需要为每个请求设置 属性。最好的选择是在 class 上创建一个接受用户和 returns 计算值的方法。像这样:
bool IsReadOnly(int userId){
return userId > 5;
}
我发现 AutoMapper 有 ProjectTo 函数可以满足我的需要,ProjectTo 会告诉 AutoMapper 的映射引擎向 IQueryable
发出一个 select 子句
我的配置示例:
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
我有一个布尔值 属性 的实体,名为 "ReadOnly",这个 属性 的值取决于哪个用户正在使用该应用程序。
在 DbContext 中,我将 属性 配置为忽略。
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Entity>().Ignore(e => e.ReadOnly);
}
}
如何设置运行时计算的正确值,这样我就不用每次都提醒计算 属性?
编辑:我在想
int loggedUserId = HttpSession.UserId;
modelBuilder.Entity<Entity>().Property(e => e.ReadOnly).Value = loggedUserId > 5;
通过这种方式,我始终可以根据登录到应用程序的用户获得正确的值。
您可以尝试使用 filter,但我不确定它是否有效,因为您需要为每个请求设置 属性。最好的选择是在 class 上创建一个接受用户和 returns 计算值的方法。像这样:
bool IsReadOnly(int userId){
return userId > 5;
}
我发现 AutoMapper 有 ProjectTo 函数可以满足我的需要,ProjectTo 会告诉 AutoMapper 的映射引擎向 IQueryable
发出一个 select 子句我的配置示例:
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