我想了解一些关于'表达'的信息。
有两个类:
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
}
我想检测,因为我希望Update
Object
有一个参考;我会用另一个代码处理它。
行
myContext.Entry(AttachedObject).Property(ex1).IsModified = true;
错误:“用户”类型上的属性“照片”不是原始或 复杂的财产。 Property方法只能与原语一起使用 或复杂的属性。使用Reference或Collection方法。
myContext.Entry(AttachedObject).Property(ex2).IsModified = true;
错误
myContext.Entry(AttachedObject).Property(ex3).IsModified = true;
答案 0 :(得分:0)
您需要确定表达式的返回类型是否为引用。所以使用代码形式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;
}