简体   繁体   English

Ef Core 2将值设置为运行时被忽略的属性

[英]Ef Core 2 set value to ignored property on runtime

I have an entity with boolean property named "ReadOnly", the value of this property depends on which user is using the application. 我有一个名为“ ReadOnly”的布尔属性的实体,此属性的值取决于使用该应用程序的用户。

In the DbContext i configured the property to be ignored. 在DbContext中,我将属性配置为忽略。

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. 这样,我始终具有基于登录到应用程序的用户的正确值。

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;
}

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 我发现AutoMapper具有满足我需要的ProjectTo函数,ProjectTo将告诉AutoMapper的映射引擎向IQueryable发出select子句

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 http://docs.automapper.org/en/stable/Queryable-Extensions.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM