自动数据库查找?

时间:2013-07-16 15:28:56

标签: c# automapper

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

例如,一个表存储一个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;
}

1 个答案:

答案 0 :(得分: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;}
}