是否可以在不拖放的情况下使用Linq-SQL? [英] Is it possible to use Linq-SQL without drag-and-drop?

查看:47
本文介绍了是否可以在不拖放的情况下使用Linq-SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想使用Linq-SQL,还必须将DB Table拖到设计器表面以创建实体类.

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

我一直喜欢我的应用程序中的完全控制权,并且不喜欢dotnet创建的类.

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

是否可以使用我自己的数据访问层实体类在Linq和DB之间提供此连接?

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

我如何完成它?

推荐答案

您可以使用Linq-to-SQL非常轻松地编写自己的类-只需画一些具有某些属性的类即可.

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

例如,这是我在一个项目中拥有的非常简单的表,并且可以很好地与Linq-to-SQL一起使用:

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

当然还有更多内容,但这向您展示了非常基础的知识,一旦您理解它就不难做.这样,您可以100%地控制您的类,并且仍然可以使用Linq-to-SQL.

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.

我从一本很棒的书 Pro ASP.NET MVC Framework 中学习了这种方法.

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

如果想了解更多内容,我所有的Linq-to-SQL类都是从头开始写在我的一个项目上的,您可以浏览

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.

这篇关于是否可以在不拖放的情况下使用Linq-SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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