来自 ObjectContext 的 EntityFramework EntityType?
我有一个具有以下签名的方法:
public voidGenerateLog
如何循环遍历我的 ObjectContext 并为我的 ObjectContext 中的每个实体调用此方法?
我知道我可以这样做:
foreach (ObjectStateEntry entry in
context.ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified))
{
string entityName = entry.Entity.GetType().Name;
}
但我不知道如何从名称的字符串表示形式转到 GenerateLog
而不是 GenerateLog
。
I have a method with this signature:
public void GenerateLog<TEntity>(TEntity entity) where TEntity : EntityObject
How can I loop through my ObjectContext and call this for each Entity in my ObjectContext?
I know that I can do this:
foreach (ObjectStateEntry entry in
context.ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified))
{
string entityName = entry.Entity.GetType().Name;
}
But I don't know how to go from a String representation of the name to GenerateLog<MYSTRING>
instead of GenerateLog<TEntity>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要从
GenerateLog
创建一个通用方法,然后调用它。在让这样的东西工作之前,我通常需要先搞乱一下,但这应该很接近YourClass
只是GenerateLog所在的类。You need to make a generic method from your
GenerateLog
and then call that. I normally need to mess around a bit before I get something like this to work, but this should be closeYourClass
is simply the class the GenerateLog is in.正如 Drew Marsh 所说,无法仅使用泛型 Type 参数的名称来调用泛型方法。因此,我只能建议您可能认为使用运行时方法解析有点垃圾的解决方案 - 尽管它会起作用...
首先,在 foreach 内分配一个动态变量,并调用名为(例如)
CallGenerateLog()
的私有方法:...为您想要记录的每种实体类型提供一个
CallGenerateLog()
重载,并具有每个都调用您的GenerateLog()
方法,例如:...等等...并提供一个包罗万象的重载,该重载将满足编译器的要求,并在您没有实体类型时被调用发现显式重载 for 。
这样做的问题包括:
您需要为每个实体类型重载
CallGenerateLog()
,因此,如果您添加要记录的新实体类型,您必须记住添加一个它的重载(尽管您可以使用 T4 模板解决此问题)运行时方法解析会产生一些开销,因此你可能必须分析该方法的执行情况并决定它是否继续给您带来任何问题。
As Drew Marsh said, there's no way to call a generic method with only the name of the generic Type argument. Because of that, I can only suggest what you may well judge to be a bit of a rubbish solution using runtime method resolution - although it would work...
Firstly, assign a dynamic variable inside the
foreach
, and call a private method named (e.g.)CallGenerateLog()
:...provide one overload of
CallGenerateLog()
for each of the Entity types you want to log, and have each one call yourGenerateLog()
method, e.g.:...etc... and provide a catch-all overload which will satisfy the compiler and be called if an Entity type you don't have an explicit overload for is found.
Problems with this include:
You need an overload of
CallGenerateLog()
for each Entity type, so if you add a new Entity type which you want to log you'll have to remember to add an overload for it (although you could address this with T4 templates)There is some overhead to runtime method resolution, so you may have to profile how well the method performs and decide if it's going to cause you any problems.