一般使用LINQ的DataContext [英] Generic with Linq DataContext

查看:137
本文介绍了一般使用LINQ的DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为用户表格。使用LINQ desinger,我将结束与以下内容:

Assume I have a table called User. Using LINQ desinger, I will end up with the following:


  • 称为文件的 User.dbml

  • 系统称为数据上下文类的 UserDataContext System.Data.Linq.DataContext

  • 一个子类类调用用户这是从用户表映射。一个UserDataContext对象有一个属性调用的用户这类型的 System.Data.Linq.Table<用户>

  • A file called User.dbml
  • A data context class called UserDataContext which subclasses from System.Data.Linq.DataContext
  • A class called User which is mapped from the User table. A UserDataContext object will have a property called Users which is of type System.Data.Linq.Table<User>.

到目前为止好。现在我想定义的Linq.Table属性JSON字符串转换为它所有子类的通用基类。因此,我将有:

So far so good. Now I want to define a generic base class that converts the Linq.Table property to JSON string for all of its subclasses. So I would have:

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

要完成该问题的代码,这里有一个例子子类:

To complete the code in the question, here's an example of a subclass:

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
}



实施GetJSONData()点

要总结,问题是如何避免在所有子类实现GetJSONData()通过让基类做。

To summarize, the question is how to avoid implementing GetJSONData() in all subclasses by letting the base class do it.

推荐答案

目前尚不清楚你想要哪个表。有可能在一个单一的数据上下文几个表。可能没有在您的特定模式,但里面肯定可以在LINQ一般为SQL。

It's not clear which table you'd want. There are potentially several tables in a single data context. There may not be in your particular model, but there certainly can be in LINQ to SQL in general.

您可以致电 DataContext.GetTable(类型) DataContext.GetTable< T> 如果这是有用的......你可以通过实体类型参数类以及上下文类型

You can call DataContext.GetTable(Type) or DataContext.GetTable<T> if that's useful... and you could parameterize your class by the entity type as well as the context type:

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

是你后?

这篇关于一般使用LINQ的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆