Linq2Sql Object Oriented Query Class

For my internship, I create a program that communicates with the database in the background. The program is superimposed in MVC (Model-View-Controller) mode.

For presentation, I want to access data through something that I called DataAccesLayer (DAL). Since this view has minimal knowledge, I want it to pass the ID for the request that I want to call. The call will be executed inside the DAL. Then, with the identifier, I want to ask the class that contains the queries in order to return the query, and then execute it inside the DAL. Image for visualization.

enter image description here

Now the problem is how to execute the request in my Read function. The code for DAL is as follows:

public class DataAccesLayer { private Queries queryloader; private RoadsoftDigitacV8DataContext db; public DataAccesLayer() { queryloader = new Queries(); db = new RoadsoftDigitacV8DataContext(); } public List Read(int ID) { IQueryable query; query = queryloader.GetQuery(ID); return query.ToList(); } } 

Code for the Queries class:

 public class Queries { private Dictionary<int, IQueryable object> queryDict; private ErrorLoggerWinLog logger; public Queries() { logger = ErrorLoggerWinLog.Instance(); queryDict = new Dictionary<int, IQueryable object>(); queryDict.Add(1, from d in db.Drivers select d); } public object GetQuery(int ID) { var query; if(queryDict.TryGetValue(ID, out query) == false) { logger.WriteLine("Queries", "Could not find the query specified", ErrorLoggerWinLog.loggerlevel.Error); } return query; } } 

I wonder if this is possible? Now it does not work. I probably forget something or something important. Does anyone have any experience with this kind of setup or should look at a completely different solution?

Edit: now it does not seem to fulfill the request, for example, I miss the command in the read function. Datacontext is populated, although this is done in another section of the program.

Edit2: Now I am studying the IRepository template, this is an excellent learning experience, thanks to everyone who took the time to comment and comment!

+6
source share
1 answer

At any time, your queryDict has only one element; the only time GetQuery() does not register an error message and does not return null when you pass 1 to it. as a result, Read(1) returns a list of all drivers, otherwise it throws a NullReferenceException , because, well, query is null.

You should use something like this:

  public class DriversDAL { private RoadsoftDigitacV8DataContext db; public DriversDAL() { db = new RoadsoftDigitacV8DataContext(); } public Driver GetDriver(int ID) { return db.Drives.Single(d => d.ID == ID); } } 

If you need a generic solution, you should use a generic Tao and repository pattern:

How to create shared data access methods (DAO) CRUD methods with LINQ to SQL

+3
source

Source: https://habr.com/ru/post/952724/


All Articles