5

当需要查找映射值时,是否有另一种方法来处理调用数据库?在映射逻辑中进行数据库调用似乎很难看。这还怎么处理?

例如,一个表存储一个 SEXID 所以使用下面的解析器我可以做这样的事情

CreateMap<StagingPerson, Person>()
  .ForMember( dest => dest.SEXID, 
     m => m.ResolveUsing<SexLookupResolver>().FromMember( src => src.Gender ) );         

public class SexLookupResolver : ValueResolver<string, int>
{
protected override int ResolveCore( string source )
{
  int id = -1;
  if (source == "Male")
     id = dataAccess.GetGenderByString("M");
  else if(source == "Female")
     id = dataAccess.GetGenderByString("F");
  else if(source == "?")
     id = dataAccess.GetGenderByString("?");
  else
     id = dataAccess.GetGenderByString("?");
  return id;
}
}

数据访问:

public int GetGenderByString(string gender)
{
  string sql = "select sexid from Sexes where sex = '" + gender "'";
  int sexid = .....
  ......
  return sexid;
}
4

1 回答 1

0

通过向类添加另一个字段来存储性别的字符串版本来解决这个问题。映射更改为映射到字符串,并且 SEXID 字段被忽略并稍后在 DAL 操作期间设置。

CreateMap<StagingPerson, Person>()
  .ForMember( dest => dest.SexString, u => u.MapFrom( src => src.Sex) )
  .ForMember( dest => dest.SEXID, u.Ignore() ) );

/// The source class
public class StagingPerson
{
  /// holds "M", "F", "U", "?", etc
  public string Gender {get;set;}
}

/// the destination class
public class Person
{
  public int SEXID {get;set;}

  // New property to store the source string value
  // looked up in the Data Access Layer to determine the sexId
  public string SexString {get;set;}
}
于 2013-10-25T18:23:39.850 回答