Ef Core 2将值设置为运行时被忽略的属性 [英] Ef Core 2 set value to ignored property on runtime

查看:620
本文介绍了Ef Core 2将值设置为运行时被忽略的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体,其布尔属性名为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆