我正在尝试为我的Entity Framework模型创建一个Generic类。
using UM4RS.persistance;
using UM4RS.Persistance;
public abstract class MyEntity<TObject> where TObject : class, IBaseEntity
{
static readonly ModelContext ModelContext = new ModelContext();
// class method to save object
public static TObject Save(TObject t)
{
if (t == null) return null;
ModelContext.Set<TObject>().Add(t);
ModelContext.SaveChanges();
return t;
}
// instance method to save the current instance
public void Save()
{
Save(this); //<- ERROR: Cannot convert MyEnttity<TObject> to TObject
// Also tried
ModelContext.Set<TObject>().Add(this); //<- Same error here
ModelContext.SaveChanges();
}
}
我的模型类继承自MyEntity
public class User : MyEntity<User>, IBaseEntity
{
...
}
最后,我要归档的是:
User usr = new User();
usr.Save(); // <- Call the instance method
答案 0 :(得分:0)
由于User
类是IBaseEntity
,而TObject
依次为var baseEntity = this as TObject;
Debug.Assert(baseEntity!=null);//assert that its not violated
Save(baseEntity);
ModelContext.Set<TObject>().Add(baseEntity);
,您可以将其投射
UPDATE tbl_Items
INNER JOIN
(SELECT *
FROM tbl_Inventory
INNER JOIN tbl_Inputs
ON tbl_Inventory.class = tbl_Inputs.class)
ON tbl_Items.PRODUCT_ID = tbl_Inputs.PRODUCT_ID
SET tbl_Items.status = tbl_Inventory.status
WHERE tbl_Items.status <> tbl_Inventory.status