C# 使用Automapper检查条件
我用的是Automapper。在其中,我将DTO映射到数据库表。在这个例子中,我需要检查一个条件,然后取值C# 使用Automapper检查条件,c#,lambda,automapper,C#,Lambda,Automapper,我用的是Automapper。在其中,我将DTO映射到数据库表。在这个例子中,我需要检查一个条件,然后取值 CreatedBy = mapper.Map<UserProperties>((from createdByUser in context.persons.Where(x => x.IsActive && x.Id == notes.CreatedBy) select createdByUser).FirstOrDefault()) 人 public s
CreatedBy = mapper.Map<UserProperties>((from createdByUser in context.persons.Where(x => x.IsActive && x.Id == notes.CreatedBy) select createdByUser).FirstOrDefault())
人
public string DisplayName { get; set; }
public int Id { get; set; }
public int RoleId{ get; set; }
public int NotesCount {get;set;}
public string Notes{get;set;}
public string Comments {get;set;}
下面的代码是启动文件中的automapper配置
映射配置文件类
在persons中,使用字段roleId
。我需要通过检查Persons中的RoleId
字段等于2这样的条件,为User properties类中的IsUser
字段分配值
如何使用automapper检查状况
Automapper版本:9.0.0您需要在映射中添加一个
FormMember
子句来添加条件-下面是一个工作示例(这花费的时间比它应有的时间长,因为您发布了代码的图像而不是实际代码。这就是为什么启用此选项,所以您应该始终发布代码,而不是图像。)
void Main()
{
var mapperConfig=
新的MapperConfiguration(mc=>mc.AddProfile());
var mapper=mapperConfig.CreateMapper();
var notAUser=新用户{RoleId=1};
var isAUser=新人{RoleId=2};
var shouldBeNotAUser=mapper.Map(notAUser);
var shouldbauser=mapper.Map(isAUser);
Console.WriteLine(shouldBeNotAUser.IsUser);
Console.WriteLine(shouldbauser.IsUser);
}
公共类映射配置文件:配置文件
{
公共映射配置文件()
{
CreateMap()
.ForMember(destination=>destination.IsUser,
options=>options.MapFrom(src=>src.RoleId==2));
}
}
类用户属性
{
公共字符串DisplayName{get;set;}
公共int Id{get;set;}
公共bool IsUser{get;set;}
public int NotesCount{get;set;}
}
阶级人士
{
公共字符串DisplayName{get;set;}
公共int Id{get;set;}
public int RoleId{get;set;}
public int NotesCount{get;set;}
公共字符串注释{get;set;}
公共字符串注释{get;set;}
}
输出:
假真的 然而
映射配置代码不必“知道”RoleID表示用户的内容。您的
Person
类应该位于知识所在的位置,因此应该具有IsUser()
方法或get-onlyIsUser
属性(具有NotMapped
属性)返回RoleId==2
:在前一种情况下,您仍然需要ForMember
,但在后一种情况下,您不会,尽管如果您确实从UserProperties
映射回Persons
,您将需要一些东西来处理它-同样,这应该在Persons
类中,而不是在映射器配置中。可能是设置角色ID的SetAsUser()
。能否显示自动映射配置代码我在说明中添加了配置代码。
public string DisplayName { get; set; }
public int Id { get; set; }
public int RoleId{ get; set; }
public int NotesCount {get;set;}
public string Notes{get;set;}
public string Comments {get;set;}