Use Dapper.Contrib with inheritance

假如想象 提交于 2019-12-13 03:13:34

问题


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);
        }
    }
}


来源:https://stackoverflow.com/questions/51140212/use-dapper-contrib-with-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!