【问题标题】:EF Expression<Func<T, object>> Properties DetectionEF 表达式<Func<T, object>> 属性检测
【发布时间】:2017-08-14 21:42:02
【问题描述】:

我想获得一些关于“表达”的信息。

有两个类:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Image Photo { get; set; }
    public virtual ICollection<Image> UserGallery { get; set; }
}
public class Image
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Size { get; set; }
}

    static void Main(string[] args)
    {
        Expression<Func<User, object>> ex1 = c => c.Name,
        ex2 = c => c.Photo,
        ex3 = c => c.UserGallery;
        DetectPropertyType(ex1);//i want to print: 'scalar'
        DetectPropertyType(ex2);//i want to print: 'related'
        DetectPropertyType(ex3);//i want to print: 'collection'

    }
    public static void DetectPropertyType(Expression<Func<User, object>> expression)
    {
        //How to detect kind of 'expression'
        //my question here
    }

我想检测,因为当我想要 UpdateObject 时,它有一个参考;我将使用其他代码处理它。

好的

myContext.Entry(AttachedObject).Property(ex1).IsModified = true;

错误:“用户”类型的属性“照片”不是原始类型或 复杂的属性。 Property 方法只能与原语一起使用 或复杂的属性。使用引用或集合方法。

myContext.Entry(AttachedObject).Property(ex2).IsModified = true;

错误

myContext.Entry(AttachedObject).Property(ex3).IsModified = true;

【问题讨论】:

  • 我认为你必须按照它所说的去做,使用ReferenceCollection而不是Property。喜欢这个myContext.Entry(AttachedObject).Reference(ex3).IsModified = true;Reference 仅用于简单属性,Reference 处理单个导航属性,Collection 处理集合。
  • 是的,我知道,但首先需要检测
  • Entry(obj).Reference(ex3).EntityEntry.State = System.Data.Entity.EntityState.Modified;
  • 啊,我明白了,您希望能够以编程方式判断您是否需要使用PropertyReferenceCollection?如果是这样,您应该更新您的问题以更清楚一点。我会看看我是否能找到任何信息如何做到这一点。

标签: c# entity-framework expression


【解决方案1】:

您需要确定表达式的返回类型是否为引用。所以使用代码形式here:

public static Type GetObjectType<T>(Expression<Func<T, object>> expr)
{
    if ((expr.Body.NodeType == ExpressionType.Convert) ||
        (expr.Body.NodeType == ExpressionType.ConvertChecked))
    {
        var unary = expr.Body as UnaryExpression;
        if (unary != null)
            return unary.Operand.Type;
    }
    return expr.Body.Type;
}

你可以这样做:

var returnType = GetObjectType(e1);

if(typeof(IEnumerable).IsAssignableFrom(returnType))
{
    myContext.Entry(AttachedObject).Collection(ex1).IsModified = true;
}
else if(returnType.IsClass && !typeof(string).IsAssignableFrom(returnType)) 
{
    myContext.Entry(AttachedObject).Reference(ex1).IsModified = true;
}
else
{
    myContext.Entry(AttachedObject).Property(ex1).IsModified = true;
}

【讨论】:

  • 假设他还可以通过检查 Collection 是否实现 IEnumerable 来检查它?
  • 不起作用。对于c =&gt; c.Name returnType.IsClass 返回true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多