将Dapper.Contrib与继承一起使用 [英] Use Dapper.Contrib with inheritance

查看:333
本文介绍了将Dapper.Contrib与继承一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


实体必须具有至少一个[Key]或[ExplicitKey]属性


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

 公共类BaseObject 
{
公共字符串Delete()
{
使用(IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings [ con]。ConnectionString)))
{
db.Delete(this);
}
}
}

  public class产品:BaseObject 
{
[Key]
public int id {get;组; }
公共字符串标题{get;组; }
公共字符串名称{get;组; }
}

执行时出现错误:

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

如果我删除继承并将Delete()方法移到Product对象中,则它可以正常工作。 / p>

有什么想法吗?

解决方案

您的 BaseObject 没有链接到任何表,因此Dapper无法理解在其上调用 Delete()



我认为在您的情况下,我只会使用扩展方法:

 公共静态类BaseObjectExtensions 
{
公共静态字符串Delete< T>(此T theObject),其中T:BaseObject
{
使用(IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings [ con] .. ))
{
db.Delete(theObject);
}
}
}


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?

解决方案

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

这篇关于将Dapper.Contrib与继承一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆