如何在EF类型名称传递到方法的参数? [英] How to pass in EF Type names into method arguments?
问题描述
我使用MVC3,EF4.1和C#。
I am using MVC3, EF4.1 and C#.
我想使用一个通用的方法来更新它存在于众多的实体类型的属性。因此,我需要在类型传递到方法作为参数。我怎么能这样做吗?
I am trying to use a generic method to update a property which exists in numerous Entity Types. Therefore I need to pass in the Type into the method as an argument. How can I do this please?
有些code:
public Boolean CompleteTask()
{
PRV myCurrentRecord = db.Task.OfType<PRV>().Single(r => r.Id == myId);
myCurrentRecord.IsComplete = true;
if (db.SaveChanges() > 0)
return true;
else return false;
}
在上面的例子中PRV是硬codeD。我想在不同类型的都有IsComplete作为一个属性来传递。
In the above example "PRV" is "hardcoded". I would like to pass in different types that all have "IsComplete" as a property.
我使用的TPH继承和刚刚意识到,我可以只使用父实体,即:
I am using TPH inheritance, and have just realised that I can just use the parent entity, ie:
Parent.IsComplete
有兴趣,但是,知道一在一个类型的通行证。
Would be interested, however, to know how one passes in a type.
感谢。
推荐答案
您可以使用的这个泛型方法:
public Boolean CompleteTask<TEntity>()
{
TEntity myCurrentRecord = db.Task.OfType<TEntity>().Single(r => r.Id == myId);
myCurrentRecord.IsComplete = true;
if (db.SaveChanges() > 0)
return true;
else return false;
}
您必须添加一个类型约束为 TEntity
,以确保它有一个 IsComplete
属性。
You have to add a type constraint for TEntity
to make sure it derives from your parent type which has an IsComplete
property.
public Boolean CompleteTask<TEntity>() where TEntity : ParentType
{
...
}
这篇关于如何在EF类型名称传递到方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!