使用 Dapper.Contrib 继承

Use Dapper.Contrib with inheritance

当尝试在属性位于继承对象中的对象中使用 Contrib 的 CRUD 方法时,我得到一个

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

错误。这是我的对象的简化版本:

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

还有这个

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

执行时出现错误:

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

如果我删除继承并将 Delete() 方法移动到 Product 对象中,它会完美地工作。

有什么想法吗?

您的 BaseObject 未链接到任何 table,因此 Dapper 无法理解对其调用 Delete()

我认为在你的情况下,我会简单地使用扩展方法:

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