我需要助攻;-)老实说不知道该怎么称呼所以如果人们提出更正确的措辞,我会更改标题以适应。
我已经编写了一个类'什么',这个类就像一个实用程序类..可以在整个应用程序的许多项目中使用。
在实用程序类中,有一个对EF DB Context的引用。这是为了我希望将结果保存到数据库中。
我想在Utility类中删除对它的依赖,而不是传递save方法。
我正在努力弄清楚你将如何做到这一点。即使用c#Action,我知道你可以传入一个预先形成的方法,即一个指向函数的指针。但是如何让指针知道我的Utility案例中的内容。
我希望我能正确地说明这一切,请协助我提供一个例子或链接。
显示代码:在这种情况下不确定是否必要。但这是一个粗略的例子。
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; }
}
所以我理解我需要为Utility创建一个本地类来删除对Person(DB)的引用,但是如何让我的函数注入以了解UtilityCase中的内容。感谢
答案 0 :(得分:2)
你需要这样的东西吗?
//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:未运行,可能包含轻微错误
答案 1 :(得分:0)
我不确定你在问什么,但为什么你需要所有这些代码?为什么你不能将Person
实体添加到Context
中的集合
var context = new Context();
context.Persons.Add(new Person {Name = name});
context.SaveChanges();
不确定为什么要在代码中保留额外的List<Persons>
。无论如何,您显示的代码实际上可以使用EF上下文中的Persons
集合直接完成