LINQ to SQL classes to my own classes - linq

I'm looking at using LINQ to SQL for a new project I'm working on, but I do not want to expose the LINQ classes to my applications. For example, do an select in link returns a System.Linq.IQueryable<> collection. As well, all the classes generated to represent the database use Table, Column, EntityRef classes and attributes. It's fine if my data access layer has LINQ dependancies, but I don't want my application to.
So my thoughts are that I will have to use the LINQ to SQL generated classes as intermediate classes that are not exposed outside of my data access layer, and create my own classes which the application can use. What is the easiest/effecient way to get the data from the LINQ to SQL classes into my own classes?

I totally agree with your thinking - I would try to avoid exposing LINQ to SQL entities directly to the world.
I would definitely recommend using a "domain model" of your own, either a 1:1 mirror of the underlying LINQ to SQL entities, or a different one.
As long as you have a domain model that is quite similar to the underlying LINQ to SQL entities, you can use tools like AutoMapper to easily shuffle data between your LINQ to SQL entities and your domain model classes. It should be pretty easy and flexible to do it that way!

Rob Conery published a webcast series entitled the MVC-Storefront where he introduces a variation of the repository pattern that accomplishes what you want.
I've used ideas from the screencast on a reasonably large project and was quite pleased with the results.
There are, however, issues with the pattern, particularly around concurrency and detached scenarios that you will want to think about up front before fully committing to it.
I detailed some of my pain with concurrency in this pattern here.

I'll be interested in the responses you get because I'm considering the exact same thing. I want to use the L2S entities classes on our backend but use much lighter-weight entities for application consumption.
Randy

I would advise against using LINQ to SQL on a new project, since Microsoft will no longer be developing this project, except for maybe fine-tuning some issues. LINQ to SQL is perfectly usable and is acceptable, but I would not advise new projects to use it. If you like LINQ to SQL, you should definately look into using Entity Framework instead of LINQ to SQL.

This is my current incarnation of how I am going about doing this:
I have a DataContext class that I created by adding a LINQ to SQL class, and droping tables onto the designer. I called the class MyDataContext and put it in a namespace called Linq. My database has a table called Tag, which generated a class, also in the Linq namespace. I changed all the accessors to internal, so they would not be visible outside of the data access layer.
namespace Linq
{
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDb")]
internal partial class MyDataContext : System.Data.Linq.DataContext
{
...
}
[Table(Name="dbo.vTag")]
internal partial class Tag
{
....
}
}
I then created a class called DataAccess which is what will be exposed to any application that references the assembly. I also created my own Tag class. The DataAccess class and my new Tag class are in a different namespace called Data to avoid collisions with the generated classes which are in the Linq namespace. I use Linq to Sql to query for an IList of Linq.Tag objects, then I use Linq to generate me a list of Data.Tag objects from the Linq.Tag objects.
I'd like to hear comments on this to see if there's a more performant way to do this, or one that requires less code. I also wasn't too happy with my use of duplicate class names (Tag) so I'm interested to hear any ideas on naming suggestions too.
namespace Data
{
public class DataAaccess
{
public IList<Tag> List_Tags()
{
using (Linq.MyDataContext dal = new Linq.MyDataContext ())
{
IList<Linq.Tag> lstTags = (from c in dal.Tags select c).ToList();
return (from tag in lstTags
select new Data.Tag()
{
ID = tag.ID,
Name = tag.Name,
Parent_ID = tag.Parent_ID
}).ToList();
}
}
}
}

What you are proposing is having two separate models. That means boilerplate code, which I've found is not necessary. I have more or less the same idea as you, but realized that this would be useless. I've suggested Entity Framework in another answer in this thread, and I want to make that point again here.
What you end up with is a model-soup, where you have to maintain two models instead of just the one. And that is definitely NOT desirable.

To go from the LINQ to SQL classes to your classes is a matter of some fairly straightfoward LINQ to Objects (or just initialisation for single objects).
More fun is going back from your model to the LINQ to SQL objects but this is fairly standard stuff (although something I'm still working out or I'd find you some specific references).

Related

Is it possible to map Linq queries from one Data Model to a query over a different data model?

I would like to provide an OData interface for my application. The examples that I have seen use EF to map the LINQ queries to SQL queries.
IMHO it this approach pretty much exposes the physical database model to the world (I know EF/NH give some flexibility, but it is limited).
What I would like the be able to do, is the following:
Define my Data Contract via some DTOs.
Have a OData Service that will let users query over my Data Contract Dtos.
Have some translation layer to translate the queries over the DTOs to queries over, let's say, EF model or NH.
Execute the translated query.
Map the results back to my Data Contracts.
Am I out of my mind or is there a solution to this problem?
I have 2 models, the "contract" model and the "persisted" model. The persisted model is what Entity Framework is mapped to. The Get method that returns an IQueryable returns a IQueryable which is just something along the lines of:
return dbContext.PersistedCustomers.Select(x => new Customer(Name = x.OtherName, ...));
At least when using DbContext as opposed to ObjectContext, Where criteria based on the contract model get translated automatically into Where criteria of the PersistedModel to be executed against the database. Hopefully the differences between the two aren't that complex that you need some weird data massaging. I'm sure there's limits to the reversal it does.
One way of doing it would be to create a ViewModel that will represent your Model and then use AutoMapper to map between them. You can use like this:
var address = _Context.Addresses.Where(p => p.AddressID == addressID).Single();
AddressVM result = Mapper.Map<AddressVM>(address);

LINQ DataContext Object Model, could it be used to manage a changing data structure

I am currently working on a project where we are rewriting software that was originally written in Visual DataFlex and we are changing it to use SQL and rewriting it into a C# client program and a C#/ASP.Net website. The current database for this is really horrible and has just had columns added to table or pipe(|) characters stuck between the cell values when they needed to add new fields. So we have things like a person table with over 200 columns because stuff like 6 lots of (addressline1, addressline2, town, city, country, postcode) columns for storing different addresses (home/postal/accountPostal/ect...).
What we would like to do is restructure the database, but we also need to keep using the current structure so that the original software can still work as well. What I would like to know is would it be possible using Linq to write a DataContext Object Model Class that could sort of interpret the data base structures so that we could continue to use the current database structure, but to the code it could look like we where using the new structure, and then once different modules of the software are rewritten we could change the object model to use the correct data structure???
First of all, since you mention the DataContext I think you're looking at Linq to SQL? I would advice to use the Entity Framework. The Entity Framework has more advanced modeling capabilities that you can use in a scenario as yours. It has the ability to construct for example a type from multiple tables, use inheritance or complex types.
The Entity Framework creates a model for you that consists of three parts.
SSDL which stores how your database looks.
CSDL which stores your model (your objects and the relationships between them)
MSL which tells the Entity Framework how to map from your objects to the database structure.
Using this you can have a legacy database and map this to a Domain Model that's more suited to your needs.
The Entity Framework has the ability to create a starting model from your database (where all tables, columns and associations are mapped) en then you can begin restructuring this model.
These classes are generated as partial so you could extend them by for exampling splitting the database piped fields into separate properties.
Have you also thought about using Views? If possible you could at views to your database that give you a nicer dataschema to work with and then base your model on the views in combination with stored procedures.
Hope this gives you any ideas.

how do you generate class for LINQ to SQL?

I am using linq to sql for my mvc 3 project. There are several ways to generate domain modal class files.
sqlmetal
Object Relational Designer
hand code
I always hand code those model class files. because files generated by sqlmetal or designer are messy. whats your opinion? whats the best way to do it.
EDIT:
I am using MVC 3, not 2. Maybe I am wrong, but this is how I validate. I gonna end up writing all those class files anyway, so whats the point to use tools to generate them???
public class User
{
[Required]
public string Password { get; set; }
[Required, Compare("Password")]
public string ComparePassword { get; set; }
}
We have hundreds of tables across multiple databases (one server). We do table first development, drag the tables onto different DBML designer files each in different folders representing different namespaces within each project. The designer files are marked not to compile, and we use a custom built T4 template that generates our code by reading from whatever DBML files are in the project. This lets us have full control of the code that's generated, so we can do things like implement an interface (IAuditable is one example where we have CreatedBy, CreatedDate, ModifiedBy, ModifiedDate). We can also put System.ComponentModel.DataAnnotations on our Linqed objects this way too without resorting to Buddy Classes. We have a second T4 template that's in charge of refreshing the DBML from the database, so we can ensure that tables have the 3 part prefix (db.schema.tbl) and so we don't have to delete and re-add to the designer. The XML just gets changed based on reading the db schema and updating the DBML. We also generate a repository/manager object for each POCO that have a few common query operations like GetByID(), and also handle commits and the audit logging. These managers get extended with all the custom queries you'd need to write against each table, and they own the DataContext. This design is sometimes known as the "Mommy-may-I?" approach, where the object Linqed to the table has to ask its manager to do everything for it.
I've found this to be a very versatile and slick way of doing L2S, and it's made our back-end development a breeze so that we can put our focus on the user experience. The only downside is that if we do associations across namespaces, you have to manually add those to the partial class yourself, because otherwise you'd have to add that foreign table to another DBML in order to draw the association. This is actually not such a bad thing as causes us to really think about the specificity of our namespaces and cut down extra ones. Using T4 this way is a great way to develop DRY (don't repeat yourself). The table definition is the only place you need to change the structure and it all propogates. Validation goes in one place, the POCO. Queries go in one place, the manager. If you want to do something similar, here's a good place to start.
Even tho the Designer generated classes are messy, what does it matter to you?
There's, I dare say, absolutely no need to ever open one of the design files.
If you need to extend any of the entities defined in your model, they are all partial classes so you can just create your own partial class of the same name and implement your stuff...
When I do use L2S, I just use the designer.

linq design patterns

I'm building an ASP web application and for the moment I have a namespace called Queries that contains the linq queries that are called from the code behind pages. The whole site will initially contain about 40 queries; more will be added later.
Should I keep all my queries in one large namespace or should I create a namespace for the queries of each page? For instance, QueriesPageA, QueriesPageB, QueriesPageC... and end up with about 10 smaller namespaces.
Thanks.
It sounds like you're building a business logic layer.
If you're using LINQ to SQL or Entity Framework, you will already have a collection of entity classes that closely represent your business domain.
I prefer to add my queries to entity classes as static methods. This keeps my queries neatly distributed (so I don't end up with one huge business logic class) and easy to find (a query that retrieves a set of users will live in the User class).
If the query produces an aggregate or report (e.g. quantity of cookies sold grouped by year), then I usually create a new class for the report. That way, the report becomes a model in its own right, which works well in an MVC architecture, if that's something you're considering.
I think splitting them out is a good idea, but it would be more readable and less confusing to create namespaces based on the data they're returning instead of the page they're originally used on, e.g. MyApp.Queries.Customers, MyApp.Queries.Orders.

.NET 3.5 Linq Datasource and Joins

Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?
If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one.
To do that, you can just use something like this:
<%# Bind("unit1.unit_name") %>
Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit_name'
I hope that makes sense.
(EDIT misunderstood the question, revising my answer to the following)
Your LinqDataSource could point to a view, which allows you to overcome the problem of not being able to express a Join in the actual element. From "How to: Create LINQ to SQL Classes Mapped to Tables and Views (O/R Designer)":
The O/R Designer is a simple object relational mapper because it supports only 1:1 mapping relationships. In other words, an entity class can have only a 1:1 mapping relationship with a database table or view. Complex mapping, such as mapping an entity class to multiple tables, is not supported. However, you can map an entity class to a view that joins multiple related tables.
You cannot put more than one object/datasource on a datagrid. You will have to build a single ConceptObject that combines the exposed properties of the part Entities. Try to use DB -> L2S Entities -> ConceptObject. You must be very contrived if the DB model matches the ConceptObject field-for-field.
You are best using a ObjectDataSource when you wnt to do more complex Linq and bind your Grid to the ObjectDataSource.
You do however need to watch out for Anonymous types that could give you some trouble, but anything is posible...

Resources