c# - Difficulty only mapping base class in Entity Framework -
i'm having difficulty figuring out how map base class in entity framework database, while preventing information classes inherit being mapped database.
i created simple example highlight difficulty there base worker
class, , child class called engineer
. reason, assume don't care store details of engineer... want database contain information in worker
class.
so i've done following:
class program { static void main(string[] args) { engineer e = new engineer(); e.name = "george"; e.focus = "software"; mydatabase db = new mydatabase(); e.save(db); } } public class mydatabase : dbcontext { public dbset<worker> workers { get; set; } public mydatabase() : base("mytempdb") { } } [notmapped] public class engineer : worker { public string focus { get; set; } } public class worker { [key] [databasegeneratedattribute(databasegeneratedoption.identity)] public int id { get; set; } public string name { get; set; } public bool save(mydatabase db) { try { if (db.workers.any(w => w.id == this.id)) { db.workers.attach(this); db.entry(this).state = system.data.entity.entitystate.modified; } else { db.workers.add((worker)this); } db.savechanges(); } catch (exception e) { console.writeline(e); return false; } return true; } }
i doing "database first" design, , database table looks like:
create table [dbo].workers ( [id] int not null primary key, [name] nvarchar(200) null, [discriminator] nvarchar(200) null )
however, when run program, still looking entity store engineer
in. i've told not map it, hoping map base class database:
system.invalidoperationexception: mapping , metadata information not found entitytype 'consoleapplication10.engineer'.
i think might have map entity new worker
entity before saving entity framework doesn't object's sub type—engineer
.
for example:
public class worker { [key] [databasegeneratedattribute(databasegeneratedoption.identity)] public int id { get; set; } public string name { get; set; } public static fromworker(worker worker) { // example of mapping entity return new worker { id = worker.id, name = worker.name, }; } public bool save(mydatabase db) { try { worker worker = worker.fromworker(this); if (db.workers.any(w => w.id == worker.id)) { db.workers.attach(worker); db.entry(worker).state = system.data.entity.entitystate.modified; } else { db.workers.add(worker); } db.savechanges(); } catch (exception e) { console.writeline(e); return false; } return true; } }
Comments
Post a Comment