Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Linq-SQL without drag-and-drop?

If i want to use Linq-SQL i also have to drag the DB Table unto the designer surface to create the entity classes.

I always like full control in my application and do not like the classes created by dotnet.

Is it possible to provide this connection between Linq and the DB using my own Data Access Layer Entity classes?

How can i get it done?

like image 786
Orson Avatar asked Dec 07 '09 11:12

Orson


People also ask

How to setup LINQ to SQL?

To install the LINQ to SQL tools, start the Visual Studio installer, choose Modify, then select the Individual Components tab, and then select LINQ to SQL tools under the Code Tools category.

What is LINQ to SQL classes?

LINQ to SQL is a component of the . NET Framework that provides a run-time infrastructure for managing relational data as objects.


2 Answers

You can write your own classes very easily using Linq-to-SQL - just involves painting your classes with some Attributes.

For Example, this is a very simple table I have in one of my projects, and it works with Linq-to-SQL just fine:

[Table(Name = "Categories")]
public class Category : IDataErrorInfo
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int Id { get; set; }
    [Column] public string Name { get; set; }
    [Column] public string ExtensionString { get; set; }
}

The code was very easy, especially if you make your property names line up with your table names (you don't have to).

Then you just need a Repository to connect to the DB:

class CategoryRepository : ICategoryRepository
{
    private Table<Category> categoryTable;
    public CategoryRepository(string connectionString)
    {
        categoryTable = (new DataContext(connectionString)).GetTable<Category>();
    }
}

Of course there is more to it, but this shows you the very basics and it is not hard to do once you understand it. This way you have 100% control over your classes and you can still take advantage of Linq-to-SQL.

I learned this approach from Pro ASP.NET MVC Framework, an awesome book.

If you want to see more, all of my Linq-to-SQL classes were written from scratch on one of my projects you can browse here.

like image 61
naspinski Avatar answered Oct 12 '22 23:10

naspinski


To avoid drag & drop you can take a look at SqlMetal.exe.

However, it sounds like you really are requesting Persistence Ignorance, and I'm not sure that this is possible with L2S - it certainly isn't possible with LINQ to Entities until .NET 4...

I once wrote a blog post on using SqlMetal.exe and subsequently modifying the generated schema - perhaps you will find it useful, although it has a different underlying motivation.

like image 36
Mark Seemann Avatar answered Oct 13 '22 00:10

Mark Seemann