鉴于以下内容:
SQL:
SuperClassTable
|
--> NumberSet (varchar(MAX))
Sample data: '110,111,112,113,114'
SubClassTable
|
--> NumberSubSet (varchar(MAX))
Sample data: '110,111,112'
SP_GetClassTables
|
--> Returns the two tables above joined on an id, based on that id.
模型:
public class SuperClass {
public IEnumerable<String> NumberSet { get; set; }
}
public class SubClass : SuperClass {
public IEnumerable<String> NumberSubSet { get; set; }
}
MAPPER:
var superMapping = CreateMap<DbSuperClass, SuperClass>();
superMapping.ForMember(dest => dest.NumberSet,
opt =>
opt.MapFrom(
src =>
!String.IsNullOrWhiteSpace(src.numberSet)
? src.numberSet.Split(',')
.Select(s => s.Trim())
.ToEnumerable()
: null));
// Both of these map the comma-delimited varchars to
// the IEnumerable<String>s in the models.
var subMapping = CreateMap<DbSubClass, SubClass>();
subMapping.ForMember(dest => dest.NumberSubSet,
opt =>
opt.MapFrom(
src =>
!String.IsNullOrWhiteSpace(src.numberSubSet)
? src.numberSubSet.Split(',')
.Select(s => s.Trim())
.ToEnumerable()
: null));
控制器:
public class Repo{
public SubClass Get(int id) {
var subClassEntry =
Context.Database.Query<DbSubClass>("SP_GetClassTables", new {value = id},
commandType: CommandType.StoredProcedure).FirstOrDefault();
var entry = Map(subClassEntry); // In-house method to take care of the mapping
return entry;
}
}
public class SubClassController {
protected Repo _repo;
// ...
public ActionResult Edit(int id) {
var model = _repo.Get(id);
return View(model);
}
}
查看:
@model SubClass
<p>
NumberSet: @(Model.NumberSet == null || !Model.NumberSet.Any() ?
"N/A"
: ( Model.NumberSet.Count() > 1
? String.Join(",", Model.NumberSet)
: Model.NumberSet.FirstOrDefault().Trim() )
)
</p>
<p>
NumberSubSet: @(Model.NumberSubSet == null || !Model.NumberSubSet.Any() ?
"N/A"
: ( Model.NumberSubSet.Count() > 1
? String.Join(",", Model.NumberSubSet)
: Model.NumberSubSet.FirstOrDefault().Trim() )
)
</p>
产生
NumberSet: 1,1,0,,,1,1,1,,,1,1,2,,,1,1,3,,,1,1,4
NumberSubSet: 110,111,112
我几乎完全不知道为什么会这样做。我尝试从映射器中删除Splitting,它创建了相同的逗号混乱。任何想法都是最受欢迎的。
(注意:这是一个更为复杂的设计,为了简洁起见我尽量简化,但我可能在这个过程中不小心遗漏了一两个重要的细节。我提前道歉!)
答案 0 :(得分:1)
我修好了。未在SuperClass.NumberSet字段的mapper类中调用映射器配置。愚蠢的错误。