扩展EF的DbContextEF、DbContext

2023-09-06 15:05:58 作者:已,足夠

我不知道,如果我所问的是要走的路。我有一个数据库第一个模型。我要添加某些常用方法给它,如更新特定表的一个特定领域。

I am not sure if what i am asking is the way to go. I have a DB first model. I want to add certain common methods to it, like updating a specific field of a specific table.

我知道我可以用适当的方法,如创建一个类做到这一点:

I know i could do this by creating a class with the appropriate methods like:

public static class MyClass
{
    public static void UpdateFieldAOfTableA(int newValue)
    {
        using(DBContext db = new DBContext())
        {
            //Update Code
            db.SaveChanges();
        }
    }
}

但有延长的DbContext的一种方式,所以我只要致电:

But is there a way of extending the DBContext, so i could just call:

DBContext.UpdateFieldAOfTableA(newValue);

我试图创建一个部分类,并添加扩展名,例如:

I tried creating a partial class and adding an extension such as:

public partial class DBContext
{
    public static void UpdateFieldAOfTableA(this DBContext db,int newValue)
    {
        //Update Code here
    }
}

不过这显然没有,我可以只程度非一般的静态类工作,这也不是一成不变的。

but this obviously didn't work as i can extent only non-generic static classes and this is not static.

你觉得什么,我试图做的是错的?你有什么想法?

Do you think what i am trying to do is wrong? What are your thoughts?

推荐答案

由于的DbContext 已经被声明为分部类,则不需要使用扩展方法。这应该工作:

Since the DBContext is already declared as a partial class, you don't need to use an extension method. This should work:

public partial class DBContext
{
    public void UpdateFieldAOfTableA(int newValue)
    {
        //Update Code here
    }
}

您现在应该能够调用 DBContext.UpdateFieldAOfTableA(为newValue);