遍历未保存的实体对象,并获取非标量属性以外的属性和值

时间:2018-10-15 02:04:36

标签: c# linq

我正在使用下面的代码循环访问未保存的实体对象。

public static void main (String[] args) throws java.lang.Exception
    {
        // your code go
        int num = 5;
        String givenNumInBinary = Integer.toBinaryString(num);
        StringBuffer output = new StringBuffer();

        for(int i = 0; i <= givenNumInBinary.length()-1;i++){
            int msb = Character.getNumericValue(givenNumInBinary.charAt(i));
            output.append(~msb);
        } 
        System.out.println(output.toString());
    }

问题在于非标量属性已包含在BPCategory Bp = new BPCategory(); Bp.Category = Category; Bp.PercentShare = PercentShare; Bp.BPCategory1 = BPCategory; Bp.DealerCode = Convert.ToString(Global.DealerCode); Bp.Status = Inactive; context.BPCategories.AddObject(Bp); var values = Bp.GetType().GetProperties().Select(x => new { property = x.Name, value = x.GetValue(Bp, null) }).ToDictionary(x => x.property, y => y.value); foreach (var items in values) { //some code } context.SaveChanges(); 中,我不打算包含。我有什么办法可以从values删除非标量属性?

请参见下图。如何不包括valuesEntityState

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要定义一个自定义导航属性类,这将帮助您在反射时检测标量或非标量属性。

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class NavigationAttribute: Attribute
{

} 

我尝试编写您的模型类,Product是一个演示导航类,您可以像这样使用其他类:

public class BPCategory 
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string PercentShare { get; set; }
    public string BPCategory1 { get; set; }
    public string DealerCode  { get; set; }
    public string Status { get; set; }

    [NavigationAttribute]
    public List<Product> Product { get; set; }
}

将此代码添加到您的代码中:

var values = Bp.GetType().GetProperties()
            .Where(x => x.GetCustomAttributes(typeof(NavigationAttribute), false).Count() != 1)
            .Select(x =>
            new
            {
                property = x.Name,
                value = x.GetValue(Bp, null)
            }).ToDictionary(x => x.property, y => y.value);

输出:仅标量属性,而无乘积:

Id, Category, PercentShare, BPCategory1, DealerCode,Status

enter image description here

答案 1 :(得分:1)

<button id='berlin' (click)="onClick('berlin')">Zoom to Berlin</button> 达到了目的。将BindingFlags参数设置为GetProperties()会从字典中删除.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)EntityState属性

EntityKey