如何在实体框架中添加remove()和.add()?

发布于 2025-02-01 02:20:10 字数 1431 浏览 2 评论 0原文

当我在“实体框架”中使用时,我如何在我的repo/controler逻辑中编写和.add(对象数据)

这是我的代码示例,带有空的方法占位符:

class Projects
{
    public static List<TProjekty> GetAll()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        EntitiesModel em = DB.GetDB();

        List<TProjekty> projects = em.TProjekties.ToList();

        sw.Stop();
        Console.WriteLine("GetAllProjects: " + sw.ElapsedMilliseconds);

        return projects;
    }

    public static List<TProjekty> GetAllActiveOnly()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        EntitiesModel em = DB.GetDB();

        List<TProjekty> projects = em.TProjekties.Where(p => p.Aktualni == true).ToList();

        sw.Stop();
        Console.WriteLine("GetAllProjects: " + sw.ElapsedMilliseconds);

        return projects;
    }

    public void Add(object data)
    {
        //var item = Entry(data);
    }

    public void Delete(object data)
    {
        //var item = Entry(data);
    }

    public static void Save(TProjekty project)
    {
        if (project == null)
        {
            return;
        }

        EntitiesModel em = DB.GetDB();
        em.Add(project);
        em.SaveChanges();

        Checker.CheckAfterEverySave();
    }
}

代码还不错,没有任何错误,但是我对adddelete的空白方法,因为我不知道我应该写它。我必须使用.NET Framework 4.8,因此我不能为.NET Core使用DB选项。

How do I can write a .Remove(object data) and .Add(object data) methods in my Repo/Controller logic when I am using in Entity Framework as the ORM? I generated Entity Model and everything works in my program, except for saving and removing entries from the database.

This is my code sample with the empty method placeholders:

class Projects
{
    public static List<TProjekty> GetAll()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        EntitiesModel em = DB.GetDB();

        List<TProjekty> projects = em.TProjekties.ToList();

        sw.Stop();
        Console.WriteLine("GetAllProjects: " + sw.ElapsedMilliseconds);

        return projects;
    }

    public static List<TProjekty> GetAllActiveOnly()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();

        EntitiesModel em = DB.GetDB();

        List<TProjekty> projects = em.TProjekties.Where(p => p.Aktualni == true).ToList();

        sw.Stop();
        Console.WriteLine("GetAllProjects: " + sw.ElapsedMilliseconds);

        return projects;
    }

    public void Add(object data)
    {
        //var item = Entry(data);
    }

    public void Delete(object data)
    {
        //var item = Entry(data);
    }

    public static void Save(TProjekty project)
    {
        if (project == null)
        {
            return;
        }

        EntitiesModel em = DB.GetDB();
        em.Add(project);
        em.SaveChanges();

        Checker.CheckAfterEverySave();
    }
}

The code is alright without any errors, but I have empty methods for the Add and the Delete, because I have no idea how should I write it. I have to use .Net framework 4.8 so I cant use DB option for .Net Core.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清欢 2025-02-08 02:20:10

您应该为此使用类型的界面,而不是尝试使用盒装对象引用,实际上您的代码在save>保存中已经在执行添加 >为你!

此解决方案不是最佳实践,仅作为对特定问题的直接回答。以这样的独立方式包装dbContext包装的整体模式(由于tpojeckty实例返回get get 方法使用不同的dbContext实例到数据持续的方法。)通常被视为反图案,在许多用例(不是全部)中,调用逻辑可以直接使用dbContext实例更好。您可以在此代码中看到添加delete或多或少地调用dbContext

中的相同方法。

public void Add(TProjekty project)
{
    EntitiesModel em = DB.GetDB();
    em.TProjektys.Add(project);
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}

public void Delete(TProjekty project)
{
    EntitiesModel em = DB.GetDB();
    em.Entry(project).State = EntityState.Deleted;
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}

注意:此代码假设您的dbset&lt;&gt;在您的dbContext > tprojekty type> dbcontext 称为em.tprojektys。请在执行前更新代码,该引用与您的dbset的名称匹配。它也可能是一个单数或适当的复数形式:em.tprojektyem.tprojekties

另外:这两种方法都坚持了数据库的更改,这就是为什么我在此解决方案中呼唤您的checker.checkaftereverysave();

如上所述,保存方法已经执行add操作,因此实际上根本不会更新记录。 保存的此代码实际上应执行以下步骤顺序:

  1. 检测数据库中提供的值是否已经存在,
  2. 如果记录不存在,则添加了记录
  3. ,或更新现有记录(如果有

架构和dbContext尚未提供实现,因此,如果您使用基于简单的整数id键,我们在这里无法提供确定的解决方案,那么我们可以使用公共惯例在id中检查零值:

public static void Save(TProjekty project)
{
    if (project == null) return;

    EntitiesModel em = DB.GetDB();
    if (project.Id > 0)
    {
        em.TProjektys.Attach(project);
        em.Entry(project).State = EntityState.Modified;
    }
    else
    {
        em.TProjektys.Add(project);
    }
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}

You should use a typed interface for this, instead of trying to use a boxed object reference, in fact your code in Save is already doing the Add for you!

This solution is not best practice and is only provided as a direct response to the specific question. The whole pattern of wrapping a DbContext in a detached way like this (detached because the TPojeckty instances returned from Get methods use a different DbContext instance to the data persisting methods.) is generally considered an anti-pattern, in many use cases (not all) it would be better for the calling logic to use the DbContext instance directly. You can see in this code, the Add and Delete more or less call the same methods in the DbContext.

public void Add(TProjekty project)
{
    EntitiesModel em = DB.GetDB();
    em.TProjektys.Add(project);
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}

public void Delete(TProjekty project)
{
    EntitiesModel em = DB.GetDB();
    em.Entry(project).State = EntityState.Deleted;
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}

NOTE: This code is assuming that the DbSet<> in your DbContext for the TProjekty type is called em.TProjektys. Please update the code with a reference that matches the name of your DbSet before executing. It may also be the singular or proper plural forms of either: em.TProjekty or em.TProjekties

Also: both of these methods are persisting the changes to the database, that is why I am calling out to your Checker.CheckAfterEverySave(); in this solution.

As mentioned above, the Save method was already performing the Add operation, so it won't actually be updating records at all. This code for Save should actually perform the following sequence of steps:

  1. detect if the provided value already exists in the database
  2. Add the record if it does not exist
  3. or Update the existing record if there is one

The schema and DbContext implementations have not been provided, so we can't offer a definitive solution here, if you are using a simple integer based Id key, then we could use the common convention of checking for a zero value in the Id:

public static void Save(TProjekty project)
{
    if (project == null) return;

    EntitiesModel em = DB.GetDB();
    if (project.Id > 0)
    {
        em.TProjektys.Attach(project);
        em.Entry(project).State = EntityState.Modified;
    }
    else
    {
        em.TProjektys.Add(project);
    }
    em.SaveChanges();

    Checker.CheckAfterEverySave();
}
风蛊 2025-02-08 02:20:10

您会像代码示例一样使用通用。

添加方法的签名应为:

public void Add<TProjekty>(TProjekty data)
  {
     //get db and use add method
  }

You shoul use Generic like in your code example.

The signature for the Add method should be :

public void Add<TProjekty>(TProjekty data)
  {
     //get db and use add method
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文