通用Linq DataContext

假设我有一个名为User的表。 使用LINQ desinger,我将得到以下结果:

  • 一个名为User.dbml的文件
  • 一个名为UserDataContext的数据上下文类,它是System.Data.Linq.DataContext的子类
  • 一个名为User的类,它从User表映射。 UserDataContext对象将具有名为Users的属性,其类型为System.Data.Linq.Table

到现在为止还挺好。 现在我想定义一个通用基类,它将Linq.Table属性转换为所有子类的JSON字符串。 所以我会:

using Newtonsoft.Json; class BasePlugin where T : System.Data.Linq.DataContext, new() { protected T DataContext = new T(); protected string GetJSONData() { //*** DataContext if of type System.Data.Linq.DataContext, therefore it won't know the Linq Table property of its subclasses return JsonConvert.SerializeObject(DataContext.Cannot_get_subclass_property_Linq_table); } } 

要完成问题中的代码,这是一个子类的示例:

 class UserPlugin : BasePlugin { //The protected member DataContext inherited from BasePlugin //has a property called Users of type System.Data.Linq.Table. //The point to to avoid implementing GetJSONData() in all subclasses } 

总而言之,问题是如何避免在基类中执行GetJSONData()。

目前还不清楚你想要哪个表。 单个数据上下文中可能存在多个表。 在您的特定模型中可能没有,但在LINQ to SQL中肯定会有。

你可以调用DataContext.GetTable(Type)DataContext.GetTable如果它有用……你可以通过实体类型和上下文类型来参数化你的类:

 class BasePlugin where TContext : DataContext, new() where TEntity : class { protected TContext DataContext = new TContext(); protected string GetJSONData() { return JsonConvert.SerializeObject(DataContext.GetTable()); } } 

这就是你要追求的吗?