Tutorial :Use LINQ generated classes directly?



Question:

LINQ will generate a set of classes from the SQL files. Should these be used directly, or should they be wrapped in another class so the model is not so dependent on the implementation?


Solution:1

You can do it either way. Generally I wrap the Linq to SQL classes in a repository, but if the app is small you can use the repository methods directly.

If the app is larger you can add a business layer.


Solution:2

If you actually need to abstract from your sql database's model, then Linq-To-Sql is probably the wrong choice. Sure, you can make it work (but that isn't what it was made for).

If you need that level of abstraction, you will want to move on to a more "enterprisey" ORM like Entity Framework. They require more configuration, which is used to specify the more intricate mappings that allow your object model and database model to not resemble each other,

On the other hand, if this is overkill then use Ling to Sql. It's simple and it's easy, as long as you can stick with its simplified approach to mappings.


Solution:3

I think it's fine to use the generated model classes directly in your business and presentation tiers - however, I would definitely encapsulate data access for those entities inside a repository pattern of some description (GetOne(), Save(), Search(), Delete() etc).

The main reason for doing so is to 'disconnect' query results before returning them to a calling layer, so that clients don't inadvertently execute queries directly against the database when they use LINQ on returned results. Eg, calling ToList() on an IQueryable<T> will return a local copy of the sequence that can be managed using plain LINQ to Objects.

It also promotes better separation of layers and less coupling, as clients will interact via interface methods on the repository, rather than use LINQ to SQL directly for data access, so if you do decide to chuck LINQ to SQL in favour of the Entity Framework (shudders), it's easier to do the refactoring.

The one exception I would make is when LINQ to SQL objects need to cross a service boundary, ie, sent as data transfer objects to or from a WCF service. In this case, I think it's a good idea to have a separate, light-weight object model that supports serialization - don't send your LINQ to SQL objects directly over the wire.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »