我试图遍历我的EF实体代码第一个对象的所有属性。我只想要我定义的属性。但是当我这样做时,它包括一个属性 “RelationshipManager”,我真的不想要。
这是对象:
public class SchoolYear
{
[Key]
public virtual int SchoolYearId { get; set; }
public virtual string SchoolYearName { get; set; }
}
以下是代码:
public static string plistFromObject<T>(List<T> data)
{
string plist = "";
plist = plist + "<array>\r\n";
foreach (var item in data)
{
// I want to exclude "relationshipmanager"
List<string> props = item.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name).ToList();
plist = plist + "<dict>\r\n";
foreach (var prop in props)
{
var val = item.GetType().GetProperty(prop).GetValue(item, null).ToString();
plist = plist + "<key>" + prop + "</key>\r\n";
plist = plist + "<string>" + System.Web.HttpUtility.HtmlEncode(val) + "</string>\r\n";
}
plist = plist + "</dict>\r\n";
}
return plist;
}
电话
[WebMethod]
public string GetSchoolYears()
{
var db = new MyEntities();
var results = (from i in db.SchoolYears
select i).ToList();
return Library.Common.plistFromObject(results);
}
答案 0 :(得分:2)
试试这样:
var xml = new XElement(
"array",
data.Select(d =>
new XElement("dict",
d.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.Name != "RelationshipManager")
.Select(
p => new [] {
new XElement("key",p.Name),
new XElement("string", p.GetValue(d, null)) }
)
)
));
请参阅demo。
答案是EF不能与你的类完全一致,但是使用特殊的动态生成代理类,所以即使你没有这样的属性,EF也可以添加它。查看更多details。
答案 1 :(得分:0)
使用Tony的回答:我能够这样做,而不必过滤掉EF动态属性。这将获得对象的实际类型
var xml = new XElement(
"array",
data.Select(d =>
new XElement("dict",ObjectContext.GetObjectType(d.GetType ()).GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Select(
p => new[] {
new XElement("key",p.Name),
new XElement("string", p.GetValue(d, null)) }
)
)
));