2014-11-03 139 views

回答

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(); 
} 
+0

+1 - 正确无误。 – TomTom 2014-11-03 14:42:11

+1

类型'T'必须是引用类型,以便将其用作通用类型或方法'System.Data.Linq.DataContext.GetTable ()'Iam中的参数'TEntity'。Iam出现此错误。 – 2014-11-03 14:51:09

+0

@GeylaniARCA这是因为GetTable方法的约束,您还需要一个类约束:'where T:class,ICommon' – 2014-11-03 14:56:26

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(); 

}