c# - Why is Entity Framework creating a discriminator column for my View Model? -
i've read quite few posts on table per type
/tpt , discriminator column, but, i'm not wiser in situation.
taking example: have mvc app has model called foo
. has 1 property called bar
stored 1 many elsewhere.
i 1 using app , didn't want spend lot of time on it, wanted quickest way add items list in bar
. because of this, made new class called fooviewmodel
derived foo
, , had string property called bartemp
.
the basic idea can type 111, 222 , 333,444
in standard text field , have edit/create controllers clear whitespace , split list on comma.
what can't figure out view model never written ef, so, why creating discriminator column.
it looked when tried scaffold migration, event tried adding bartemp
db.
i have since created new type called same, instead of deriving, have foo
, bartemp
properties in works expected, but, still don't happened , learn more.
it's because entityframework parses hierarchy. because current code doesn't ever save bartemp
, there's nothing explicitly stopping writing:
context.bars.add(new bartemp());
there's nothing entityframework can detect above. so, plays safe , assumes if inherit entity, subclass also entity. that's correct assumption - , shouldn't make view models inherit entity. neither should properties. i'm unsure how you've setup current code, classes should distinct. example, should like:
class bartemp { public string barid { get; set; } public string foos { get; set; } } class bar { public string barid { get; set; } public icollection<foo> foos { get; set; } } class foo { public string id { get; set; } public bar bar { get; set; }
your view model should know nothing entities, , entities should know nothing view models. code accepting input should work converting view model entity. example:
private void update(bartemp bartemp) { var bar = context.bars.getbyid(bartemp.barid); foreach (var foo in bartemp.foos.split(",")) { var foo = context.foos.getbyid(foo); bar.foos.add(foo); } context.save(); }
don't take above example of code - it's extremely inefficient - should show example of conversions should take place, , how keep entities , view models separate.