假设我有一个名为User的表.使用LINQ desinger,我将得到以下结果:
到现在为止还挺好.现在我想定义一个通用基类,它将Linq.Table属性转换为所有子类的JSON字符串.所以我会:
using Newtonsoft.Json;
class BasePlugin<T> 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);
}
}
Run Code Online (Sandbox Code Playgroud)
要完成问题中的代码,这是一个子类的示例:
class UserPlugin : BasePlugin<UserDataContext>
{
//The protected member DataContext inherited from BasePlugin
//has a property called Users of type System.Data.Linq.Table<User>.
//The point to to avoid implementing GetJSONData() in all subclasses
}
Run Code Online (Sandbox Code Playgroud)
总而言之,问题是如何通过让基类执行它来避免在所有子类中实现GetJSONData().
目前还不清楚你想要哪个表.单个数据上下文中可能存在多个表.在您的特定模型中可能没有,但在LINQ to SQL中肯定会有.
您可以调用DataContext.GetTable(Type)或者DataContext.GetTable<T>如果它有用......并且您可以通过实体类型以及上下文类型来参数化您的类:
class BasePlugin<TContext, TEntity> where TContext : DataContext, new()
where TEntity : class
{
protected TContext DataContext = new TContext();
protected string GetJSONData()
{
return JsonConvert.SerializeObject(DataContext.GetTable<TEntity>());
}
}
Run Code Online (Sandbox Code Playgroud)
这就是你要追求的吗?
| 归档时间: |
|
| 查看次数: |
2222 次 |
| 最近记录: |