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
169 views
in Technique[技术] by (71.8m points)

c# - How to get all names of properties in an Entity?


What I'm trying to do is to pass an entity object to method and return all the names of the properties in it.
I'm using this code to get all the props names :

return classObject.GetType().GetProperties();

The problem is that this code return "EntityKey" and "EntityState" as properties whe I use it with Entity Object.
Is there any way to do it ?

Thanx in advance

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You want all direct properties, but not the properties of the base type, which in your case is EntityObject:

var type = classObject.GetType();
//alternatively call out directly: typeof(EntityObject).GetProperties()...
var basePropertyNames = type.BaseType.GetProperties().Select(x => x.Name);
var props = type.GetProperties().Where(p => !basePropertyNames.Contains(p.Name));

This sample assumes there is a base type (which is the case for DB first), refactor when that is not guaranteed.

Edit from @Matt's comment: All of the above is unnecessary, could slap my head for not thinking of this - just use the right binding flags:

return classObject.GetType().GetProperties(BindingFlags.DeclaredOnly | 
                                           BindingFlags.Public | 
                                           BindingFlags.Instance);

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

...