vendredi 17 avril 2015

Dapper mapping issue concerning comma-delimited varchar field

Given the following:


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.


MODELS:



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


CONTROLLER:



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


VIEW:



@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>


PRODUCES:



NumberSet: 1,1,0,,,1,1,1,,,1,1,2,,,1,1,3,,,1,1,4

NumberSubSet: 110,111,112


I'm almost completely at a loss as to why it would do this. I tried removing the Splitting from the mapper and it created the same mess of commas. Any thoughts are most welcome.


(Note: this is from a much more complicated design that I tried my best to simplify for the sake of brevity, but I may have accidentally omitted an important detail or two in the process. My apologies in advance!)


Aucun commentaire:

Enregistrer un commentaire