开发者

ASP.NET mvc linq 2 SQL model : where is the business logic?

I'm building a first MVC app in ASP.NET and I'm using link2SQL model to work with data. All tutorials on the microsoft site let you write LINQ code in the controller to get data and pass it to the view, like this:

 Function Index() As ActionResult
        Dim datacontext As New ErrorVaultDataContext
        Dim questions = From q In datacontext.Questions
                            Where q.fk_status_id = 1
                            Order By 开发者_运维技巧q.date Descending
                            Select q
        Return View(questions)
    End Function

That works, but it's confusing me on where to place my business logic. I would like to implement business logic like "can this user get this data?" in this simple example.

Does anyone know how this works in conjunction with linq 2 SQL?


This LINQ query is the business logic. The problem is that in this example it is hardcoded in the controller thus making it tied to the database.

You could abstract it into an interface which will perform this query so that your controller is no longer dependent on a datacontext. Then you could have an implementation of this interface which will perform the actual data access:

Public Interface IBusinessRepository
    Function GetQuestions(statusId As Integer) As IEnumerable(Of Question)
End Interface

Public Class BusinessRepositorySql
    Implements IBusinessRepository
    Public Function GetQuestions(statusId As Integer) As IEnumerable(Of Question) Implements IBusinessRepository.GetQuestions
        ' TODO: Perform the data access here
        Throw New NotImplementedException()
    End Function
End Class

Then the controller could use the business logic (In this case all it needs is to get questions filtered by some condition):

Public Class HomeController
    Inherits Controller
    Private ReadOnly _repository As IBusinessRepository
    Public Sub New(repository As IBusinessRepository)
        _repository = repository
    End Sub

    Public Function Index() As ActionResult
        Dim questions = _repository.GetQuestions(1)
        Return View(questions)
    End Function
End Class

Then you could build a custom controller factory that will inject the proper implementation in the controller.


you need to look at patterns beyond MVC for instance the Repository pattern may be a good place to put the LIN2SQL then build a BLL (Business Logic Layer) between that and your controllers to do the business logic


I agree with Pharabus, regardless of which presentation layer you're using (webforms vs. mvc) you probably want to encapsulate your business logic in its own layer. That way your controller actions would make calls to the service/business layer objects instead of making use of the ORM (EF/linq2sql) context directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜