C# 延迟保存实现
本文关键字:实现 保存 延迟 | 更新日期: 2023-09-27 18:33:23
我需要帮助;-(老实说,不知道该怎么称呼它,所以如果人们想出更正确的措辞,我会改变标题以适应。
我已经为"无论什么"编写了一个类,该类就像一个实用程序类..可以在整个应用程序中的许多项目中使用。
在实用程序类中,有一个对 EF DB 上下文的引用。这是当我想将结果保存到数据库中时。
我想删除对实用程序类中的依赖,而是传入 save 方法。
我正在努力弄清楚你会怎么做。 即使用 C# 操作,我知道您可以传入要预成型的方法,即指向函数的指针。但是我如何让该指针知道我的实用程序案例中的事情。
我希望我的措辞正确,请协助举例或链接到我正在讨论的内容。
显示代码:在这种情况下不确定是否必要。但这里有一个粗略的例子。
public class UtilityCase
{
public List<Person> Persons = new List<Person>();
public void AddPerson(string name)
{
Person newPerson = new Person {Name = name};
Persons.Add(newPerson);
if (Persons.Count > 10)
{
PersistClear();
}
}
public void PersistClear()
{
//I want to be able to Set this from outside of the UtilityCase
var context = new Context();
//I want to remove the referance to the Entity (DB) Person
foreach (Person item in Persons)
{
//add person to db
}
context.saveChanges();
Persons.Clear();
}
}
数据库实体案例
public class Person
{
public string Name { get; set; }
}
所以我知道我需要为实用程序创建一个本地类以删除对 Person (DB( 的引用,但是我如何让我的函数注入以了解 UtilityCase 中的内容。谢谢
你需要这样的东西吗?
//doesn't depends on specific Entity Data Model
public class UtilityCase
{
public List<EntityObject> Persons = new List<EntityObject>();
private readonly Action<IEnumerable<EntityObject>> _saveImpl;
public UtilityCase(Action<IEnumerable<EntityObject>> saveImpl)
{
_saveImpl = saveImpl;
}
...
public void PersistClear()
{
_saveImpl(Persons);
}
}
从具有特定实体数据模型(上下文(的另一个项目中调用它:
UtilityCase uc=new UtilityCase((col) =>
{
//I want to be able to Set this from outside of the UtilityCase
var context = new Context();
//I want to remove the referance to the Entity (DB) Person
foreach (EntityObject item in col)
{
//add person to db
context.Persons.Add((Person)item));
}
context.SaveChanges();
});
PS:未运行,可能包含小错误
我不确定你在问什么,但为什么你需要所有这些代码,为什么你不能将Person
实体添加到集合中,比如Context
var context = new Context();
context.Persons.Add(new Person {Name = name});
context.SaveChanges();
不知道为什么要在代码中维护额外的List<Persons>
。 无论如何,您显示的代码实际上可以直接使用 EF 上下文中存在的 Persons
集合来完成