3 层 LINQ

发布于 2024-07-22 08:15:07 字数 806 浏览 5 评论 0原文

目前我正在设计我的学位项目。 前几天开始学习LINQ。 我发现它很有趣并计划在我的项目中使用它,但现在我在某些时候感到困惑。

当我将 LINQ 添加到 SQL 类时,它会针对数据库中的每个表自动生成实体类。

假设我的数据库中有两个表:

用户
项目
UserProjects(联合表)

和代表哪个用户与哪个项目关联的联合表。

LINQ to SQL 类自动为我生成这三个类。 现在我应该创建单独的(用户和项目)类作为业务对象还是使用这些自动生成的实体?

此外,要使用数据库功能,我们需要使用三层架构。 我可以直接从 BLL 调用 LINQ DAL 方法吗?还是需要创建单独的 DAL 来调用 LINQ DAL 的方法?

class UserBLL

{
    public void saveUser(String username, String password)
    {
         // here I am calling LINQ DAL from by BLL
         UserDataContext db = new UserDataContext();
         User u =new User {Username = username, Password = password};
        db.user.InsertOnSubmit(u);
       db.SubmitChanges();
    }

}

上面的方法调用顺序可以吗?

Currently I am working on the design of my degree project. Some days ago I began studying LINQ. I found it was interesting and planned to use it in my project but now I am getting confused at some point.

When I add the LINQ to SQL class it auto generates entities classes against each table in database.

Suppose I have two tables in database:

User
Projects
UserProjects (joint table)

and a joint table that represents which user is associated with which project.

LINQ to SQL class auto generates these three classes for me. Now shall I create separate (User and Project) classes as Business Object or use these auto generated entities?

Also, to use database functionality we are required to use 3 tier architecture. Can I directly call LINQ DAL method from my BLL or do I need to create separate DAL which will call a method of the LINQ DAL??

class UserBLL

{
    public void saveUser(String username, String password)
    {
         // here I am calling LINQ DAL from by BLL
         UserDataContext db = new UserDataContext();
         User u =new User {Username = username, Password = password};
        db.user.InsertOnSubmit(u);
       db.SubmitChanges();
    }

}

Is the above method calling sequence fine?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野却迷人 2024-07-29 08:15:07

Linq To SQL 非常适合单层设计。 对于断开连接的模型多层环境来说不太好。

上面的代码仅将单个用户插入数据库。 如果您启动 MSSQL SQL Server Profiler 或将日志连接到 Visual Studio 中的输出。 您应该看到

//Hookup the log to the output in visual studio
using (var db = new UserDataContext()) {
    db.Log = Console.Out;
}

INSERT INTO User VALUES (value1, value2, value3,...)

要更新用户,您的代码应该类似于

public void UpdateUser(String username, String password, int userId)
{
     using (var db = new UserDataContext()) {
         //Get Row From Database Marching Id
         var user = db.user.Single(p => p.Id = userId);
         //Update Values
         user.Username = username;
         user.Password = password;
         //Save To The Database
         db.SubmitChanges();
     }
}

//Get All Users From Database
public IEnumerable<User> GetAllUsers()
{
     using (var db = new UserDataContext()) {
         //Get Row From Database Matching Id
         var users = from user in db.user
                    select user;
         return users.ToList();
     }
}

//To display the data just enumerate through the enumeration that is returned.
var users = BusinessInstance.GetAllUsers();
foreach (var user in users) {
    //user is the current item
}

您应该在每次执行工作单元时使用数据库合同。 (因为数据库上下文默认使用事务,这可能会变得丑陋,不要担心构建数据库上下文的性能!

通常当您使用多层环境时,您会创建一个通过线路(网络)传递时,将 POCO 分开。

NCommon 是 Linq to Sql 的一个很好的抽象,应该处理业务验证和规则。

笔记。 在数据库中散列密码值是一种很好的做法。

查看 ScottGu 的博客,了解有关 linq 的快速问答和基础知识

Linq To SQL is great for single tier design. Not so great for a disconnected model or multi tier environment.

The above code only inserts a single User into the database. If you fire up MSSQL SQL Server Profiler or connect up the log to the output in visual studio. You should see

//Hookup the log to the output in visual studio
using (var db = new UserDataContext()) {
    db.Log = Console.Out;
}

INSERT INTO User VALUES (value1, value2, value3,...)

To update the the user your code should look at somthing like

public void UpdateUser(String username, String password, int userId)
{
     using (var db = new UserDataContext()) {
         //Get Row From Database Marching Id
         var user = db.user.Single(p => p.Id = userId);
         //Update Values
         user.Username = username;
         user.Password = password;
         //Save To The Database
         db.SubmitChanges();
     }
}

//Get All Users From Database
public IEnumerable<User> GetAllUsers()
{
     using (var db = new UserDataContext()) {
         //Get Row From Database Matching Id
         var users = from user in db.user
                    select user;
         return users.ToList();
     }
}

//To display the data just enumerate through the enumeration that is returned.
var users = BusinessInstance.GetAllUsers();
foreach (var user in users) {
    //user is the current item
}

You should make your that you are using your database contract every time you do a unit of work. (because the database context using transaction by default, and this can get ugly, don't bother about performance with constructing the database context!)

Usually when you work with a multi tier environment, you would create a seperate POCO's when passing them over the wire(network).

NCommon is a great abstraction for Linq to Sql, should handle business validation and rules.

Note. Its good practice to hash password values in a database.

Check out ScottGu's blog for a quick q&a and basics on linq

智商已欠费 2024-07-29 08:15:07

我通常为每个 BLL 对象创建一个类范围的数据上下文。

我还创建了 2 个构造函数,其中一个用于创建数据上下文,另一个用于接受数据上下文。 第二个是这样我可以传递来自其他 BLL 对象的数据上下文。

这允许您对可能来自 2 个不同 BLL 对象的对象执行数据库操作,同时仍然保持良好的关注点分离。 您还需要将数据上下文公开为公共只读,以便可以传递它。

需要注意的是,DataContext 对象不必显式处置,更多信息请参见此处。 但基本上 DataContext 只会在 BLL 对象的生命周期内存在。 如果您确实需要释放资源(即您已完成跟踪更改),则可以显式处置它。

例如

public class UserBLL
{
    private readonly UserDataContext context;

    public UserBLL() : this(new UserDataContext())
    {
    }

    public UserBLL(UserDataContext context)
    {
        this.context = context
    }

    public UserDataContext Context { get { return context; } }

    public void saveUser(String username, String password)
    {
         // here i am callsing LINQ DAL from by BLL
         User u = new User {Username = username, Password = password};
         Context.Users.InsertOnSubmit(u);
         Context.SubmitChanges();
    }
}

I normally create a class scoped datacontext for each of my BLL objects.

I also create 2 constructors, 1 that creates a datacontext and another that accepts a datacontext. The second is so that I can pass around a datacontext from other BLL objects.

This allows you to perform database operations on objects that may have come from 2 different BLL objects whilst still retaining a nice separation of concerns. You will also need to expose the datacontext as public readonly so that it can be passed around.

Something to note is that a DataContext object doesn't have to be explictly disposed, more info here. But basically the DataContext will only live for the lifetime of the BLL object. You can explicitly dispose of it though if you really need to free up the resources (i.e. you've finished tracking changes).

e.g.

public class UserBLL
{
    private readonly UserDataContext context;

    public UserBLL() : this(new UserDataContext())
    {
    }

    public UserBLL(UserDataContext context)
    {
        this.context = context
    }

    public UserDataContext Context { get { return context; } }

    public void saveUser(String username, String password)
    {
         // here i am callsing LINQ DAL from by BLL
         User u = new User {Username = username, Password = password};
         Context.Users.InsertOnSubmit(u);
         Context.SubmitChanges();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文