Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取属性的值_C#_Entity Framework_Linq_Entity Framework 6_Entity Framework 4 - Fatal编程技术网

C# 如何获取属性的值

C# 如何获取属性的值,c#,entity-framework,linq,entity-framework-6,entity-framework-4,C#,Entity Framework,Linq,Entity Framework 6,Entity Framework 4,大家好,我遇到了下一个问题: public class Document { public Header Header {get;set;} public Footer Footer{get;set;} public string Text{get;set;} public string Description{get;set;} public int NumberOfPages{get;set;} } public class Header {

大家好,我遇到了下一个问题:

public class Document
{
    public Header Header {get;set;}
    public Footer Footer{get;set;}
    public string Text{get;set;}
    public string Description{get;set;}
    public int NumberOfPages{get;set;}
}
public class Header
{
    public int Id{get;set;}
    public string Text{get;set;}
}
public class Footer
{
    public int Id{get;set;}
    public string Text{get;set;}
}
假设我有这个域,我想复制文档的所有基本属性和非基本属性,比如页眉和页脚,我只想复制文本

我的下一个代码只是复制基本属性:

public static List<DataPropertyReport> GetPrimitiveProperties<T>(T entity)
{
    var properties = entity.GetType().GetProperties();    
    List<DataPropertyReport> info = new List<DataPropertyReport>();

    foreach (var property in properties)
    {
        Object value = property.GetValue(entity, null);
        Type type = value != null ? value.GetType() : null;

        if (type != null && 
               (type.IsPrimitive || 
                type == typeof(string) || 
                type.Name == "DateTime"))
        {
            var name = property.Name;
            info.Add(new DataPropertyReport(name, value.ToString(), 1));
        }
    }    
    return info;
}
公共静态列表GetPrimitiveProperties(T实体) { var properties=entity.GetType().GetProperties(); 列表信息=新列表(); foreach(属性中的var属性) { 对象值=property.GetValue(实体,null); Type Type=value!=null?value.GetType():null; if(type!=null&& (type.IsPrimitive | | type==typeof(字符串)| type.Name==“日期时间”)) { var name=property.name; Add(新的DataPropertyReport(name,value.ToString(),1)); } } 退货信息; } 您可以对非原语类型调用
ToString()
,只需调用重载:

public class Header
{
    public int Id { get; set; }
    public string Text { get; set; }

    public override string ToString()
    {
        return Text;
    }
}
public class Footer
{
    public int Id { get; set; }
    public string Text { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

并将if改为if(type!=null),非常感谢。这非常简单,我认为没有问题,很乐意提供帮助。