Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

c# - unexpected GetType() result for entity entry

While I iterating through ObjectStateEntries I expected [t] variable name will be MY_ENTITY

foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
{
    Type t = entry.Entity.GetType();
    ...
}

but real I have

System.Data.Entity.DynamicProxies.MY_ENTITY_vgfg7s7wyd7c7vgvgv.....

How can I determine can I cast current entry to MY_ENTITY type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get the original entity type of a proxy type by

ObjectContext.GetObjectType(entity.GetType())

This is a static method of ObjectContext, so you can readily use in in a DbContext environment.

If for some reason you need the actual entity as its original type you can use the pattern

var entity = entry.Entity as MyEntity;
if (entity != null)
{
    ...
}

This is slightly more efficient than

if (entry.Entity is MyEntity)
{
    var entity = (MyEntity)entry.Entity;
    ...
}

because the latter snippet casts the object twice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...