我想通过使用相同的功能来获取实体。
public static T getById<T>(int Id)
{
myDataContect db = new myDataContect();
return (from u in db.GetTable<T> where u.Id == Id select u).FirstOrDefault();
}
如何编写有效的功能?有什么想法吗?
答案 0 :(得分:6)
您可以创建一个声明Id
属性的接口,并在您的实体中实现它。然后你就可以添加这样的约束:
// you can figure out a better name this just for example
public interface ICommon
{
int Id { get; set; }
}
public static T getById<T>(int Id) where T : class, ICommon
{
myDataContect db = new myDataContect();
return (from u in db.GetTable<T> where u.Id == Id select u).FirstOrDefault();
}
答案 1 :(得分:0)
public interface ID
{
int Id { get; }
}
public class IDImpl : ID
{
public int Id { get; private set; }
}
public static T GetById<T>(int id) where T : ID
{
var myDataContect db = new myDataContect();
return (from u in db.GetTable<T> where u.Id == id select u).FirstOrDefault();
}