Use Dapper.Contrib with inheritance

2019-08-21 08:10发布

问题:

When trying to use Contrib's CRUD methods in an object where the properties are in an inherited object I get an

Entity must have at least one [Key] or [ExplicitKey] property

error. Here is a simplified version of my objects:

public class BaseObject
{
    public string Delete()
    {
            using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
            {
                db.Delete(this);
            }
    }
}

and this

public class Product: BaseObject
{
    [Key]
    public int id { get; set; }
    public string title { get; set; }
    public string name { get; set; }
}

I get the error when I execute:

Product product = new Product() {id = 1};
product.Delete();

If I Remove the inheritance and move the Delete() method into the Product object it works flawlessly.

Any ideas?

回答1:

Your BaseObject is not linked to any table so calling Delete() on it could not be understood by Dapper.

I think that in your case, I would simply use an extension method:

public static class BaseObjectExtensions
{
    public static string Delete<T>(this T theObject) where T : BaseObject
    {
        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString))
        {
            db.Delete(theObject);
        }
    }
}