generics - C# - Is it possible to pass a derived type from a BaseModel to a Repository<T> that needs the type? -
so have repository class needs type.
i have basemodel class other models derived from.
right have have new repository() call save, update, delete, etc.
i able incorporate methods basemodel, can create object , call myobject.save(); call create repository , use it.
so this:
public class repository<t> { public void save(t entity) { // save here! } } public class basemodel { public string id { get; set; } public datetime created { get; set; } public void save() { // line needs type t. how pass this? using(var repository = new repository<t>()) { repository.save(this); } } } public class derivedmodel : basemodel { public string name { get; set; } }
note: not using entity framework.
so result of
var myentity = new derivedmodel() { name = "my entity"; }; myentity.save();
if don't want use reflection create repository, use derived type type parameter base class, example:
public class basemodel<t> // t derived type { public string id { get; set; } public datetime created { get; set; } public void save() { // t derived type using(var repository = new repository<t>()) { repository.save(this); } } } public class repository<t> { // save method must use base type here public void save(basemodel<t> item ) { } } // basemodel derived type type parameter public class derivedmodel : basemodel<derivedmodel> { public string name { get; set; } }
Comments
Post a Comment