I have the following classes (trimmed to only show the basic structure):
public abstract class BaseModel { public bool PersistChanges() { // Context is of type 'ObjectContext' DatabaseHelper.Context.SafelyPersistChanges(this); } } public static class ObjectContextExtensions { public static bool SafelyPersistChanges<T>(this ObjectContext oc, T obj) { // Persist the object using a transaction } } [Persistent('LEADS')] public class Lead : BaseModel { // Extra properties } public class LeadsController : Controller { public ActionResult Save(Lead lead) { lead.PersistChanges() } }
My Lead class derives from BaseModel, which contains a method to persist the object’s changes to the database using a transaction. I implemented the transactional persist with an extension method. The problem is that by passing this to SafelyPersistChanges in my BaseModel class, the generic T on the extension method is set to BaseModel. However, since BaseModel isn’t marked as a persistent object (which it cannot be), the ORM framework throws an exception.
Example:
Lead lead = LeadRepository.FindByNumber(2); lead.SalesmanNumber = 4; // Calls 'ObjectContextExtensions.SafelyPersistChanges<BaseModel>(BaseModel obj)' // instead of 'ObjectContextExtensions.SafelyPersistChanges<Lead>(Lead obj)' lead.PersistChanges();
The above block raises the following exception:
Cannot create mapping for type ‘SalesWeb.Data.BaseModel’ without persistent attribute.
Any ideas?
Extension Methods are statically bound at compile time. At the point in which SafelyPersistChanges is called, this is typed as BaseModel and hence your exception. In order to get the behavior you want, you’ll either need to do an ugly if statement with lots of casting or force the call to the derived class.
Make PersistChanges an abstract method. Then implement the call in the derived classes with exactly the same code.
Now this will properly be Lead