如何将 属性 动态转换为未知的 class 并在 C# Entity Framework 中对其执行检查?
How to dynamically cast a property to an unknown class and perform a check on it in C# Entity Framework?
我正在尝试将一系列功能放在一起以供 Entity Framework 使用。我的想法是,我想将通用 类 全部传递到一个例程中,然后让例程 "type" 为我执行并相应地执行。我似乎无法弄清楚如何将 Class 与其 PropertyType 结合起来。
public void AddUpdate(string classType, Object o)
{
//This gets the Type of my Class Object ok.
Type mType = Type.GetType(GetType().Namespace + "." + classType, true);
var meContext = new ClsContext(_ConnectionString);
//This retrieves the correct primary key for my the Class Object.
string key = FncGetPrimaryKey(meContext, classType + "s");
//I've tried this as a PropertyInfo as well instead of a Var
var keyID = o.GetType().GetProperty(key);
//I've tried this as Var as well as Dynamic
dynamic obj = o;
//Now I'm stuck, because I want to evaluate the property,
//but I get an error "<MyClass> does not contain a reference for 'keyID'
if (obj.keyID == 0) //ERROR ON THIS LINE
{
meContext.Entry(o).State = EntityState.Added;
}
else
{
meContext.Entry(o).State = EntityState.Modified;
}
meContext.SaveChanges();
}
虽然,我不完全明白你为什么要这样,但我想,我明白你想要达到的目的。如果我想添加一些公共对象,我就是这样做的:
public void AddUpdate<T>(T obj) where T : IEntity
{
using(var ctx = new ClsContext(_ConnectionString))
{
if (obj.keyID == 0)
{
ctx.Entry(o).State = EntityState.Added;
}
else
{
ctx.Entry(o).State = EntityState.Modified;
}
ctx.SaveChanges();
}
}
public interface IEntity
{
int keyId {get;set;}
}
尝试:
var keyValue = keyID.GetValue(o);
if (keyValue.Equals(0)) {...
我正在尝试将一系列功能放在一起以供 Entity Framework 使用。我的想法是,我想将通用 类 全部传递到一个例程中,然后让例程 "type" 为我执行并相应地执行。我似乎无法弄清楚如何将 Class 与其 PropertyType 结合起来。
public void AddUpdate(string classType, Object o)
{
//This gets the Type of my Class Object ok.
Type mType = Type.GetType(GetType().Namespace + "." + classType, true);
var meContext = new ClsContext(_ConnectionString);
//This retrieves the correct primary key for my the Class Object.
string key = FncGetPrimaryKey(meContext, classType + "s");
//I've tried this as a PropertyInfo as well instead of a Var
var keyID = o.GetType().GetProperty(key);
//I've tried this as Var as well as Dynamic
dynamic obj = o;
//Now I'm stuck, because I want to evaluate the property,
//but I get an error "<MyClass> does not contain a reference for 'keyID'
if (obj.keyID == 0) //ERROR ON THIS LINE
{
meContext.Entry(o).State = EntityState.Added;
}
else
{
meContext.Entry(o).State = EntityState.Modified;
}
meContext.SaveChanges();
}
虽然,我不完全明白你为什么要这样,但我想,我明白你想要达到的目的。如果我想添加一些公共对象,我就是这样做的:
public void AddUpdate<T>(T obj) where T : IEntity
{
using(var ctx = new ClsContext(_ConnectionString))
{
if (obj.keyID == 0)
{
ctx.Entry(o).State = EntityState.Added;
}
else
{
ctx.Entry(o).State = EntityState.Modified;
}
ctx.SaveChanges();
}
}
public interface IEntity
{
int keyId {get;set;}
}
尝试:
var keyValue = keyID.GetValue(o);
if (keyValue.Equals(0)) {...