Entity Framework Code First: Table Per Hierarchy, doesn't popluate custom discrimiator field -
i using table per hierarchy (tph) architecture work existing database schema. when attempt use custom discriminator field name dbentityvalidationexception:
property: coursetype error: coursetype field required.
models
public abstract class course { public int id { get; set; } public string name { get; set; } public string coursetype { get; set; } } public class onlinecourse : course { public string url { get; set; } } public class onsitecourse : course { public string location { get; set; } }
entity type configurations
public class coursemap : entitytypeconfiguration<course> { public coursemap() { this.haskey(x => x.id); this.property(x => x.name).hasmaxlength(100).isrequired(); this.property(x => x.coursetype).hasmaxlength(128).isrequired(); } } public class onlinecoursemap : entitytypeconfiguration<onlinecourse> { public onlinecoursemap() { this.property(x => x.url).hasmaxlength(500); } } public class onsitecoursemap : entitytypeconfiguration<onsitecourse> { public onsitecoursemap() { this.property(x => x.location).hasmaxlength(100); } }
data context
public class entitycontext : dbcontext { public entitycontext(): base("name=entitycontext") { } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.configurations.add(new coursemap()); modelbuilder.configurations.add(new onlinecoursemap()); modelbuilder.configurations.add(new onsitecoursemap()); modelbuilder.entity<course>() .map<onlinecourse>(x => x.requires("coursetype").hasvalue("online")) .map<onsitecourse>(x => x.requires("coursetype").hasvalue("onsite")); } public dbset<course> courses { get; set; } }
code executed
using (var ctx = new entitycontext()) { ctx.courses.add(new onlinecourse() { name = "online 1", url = "http://www.online.com" }); ctx.savechanges(); }
i have expected exception "coursetype cannot used discriminator , mapped coulmun" (i evidently don't remember correct error message). coursetype
can't part of model mapped column when discriminator. usual pattern see in mapping configuration (as have). else.
so may if remove coursetype
course
. hope don't need other logic.
Comments
Post a Comment