正确引用多层应用程序中的类和类成员

本文关键字:成员 应用程序 引用 | 更新日期: 2024-09-20 03:23:01

我对asp.net应用程序有点困惑,因为我无法构建项目,并出现以下错误:

Error 46 The type 'App.DAL' is defined in an assembly that is not referenced. You must add a reference to assembly 'App.DAL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. ....

基本上,该解决方案有3个项目:

  1. App.DAL
  2. App.BLL//参考DAL
  3. 应用程序项目//参考BLL

在DAL,我有一个名为学生的公共课程

namespace App.DAL
{
   public class Student
   {
    public Student(){} //Default Constructor
    private Int16 _StudentID = -1;
    // Public Variables
    public Int16 StudentID
    {
        get { return _StudentID; }
        set { _StudentID= value; }
    }
    public Student MyMethod()
    {
        // return Object of Student Type;
    }
   }
}

我的App.BLL类是:

namespace App.BLL
{
   [Serializable]
   public class Student: DAL.Student
   {
    public Student(){} //Default Constructor
    // Public Variables
    public Int16 StudentID_BLL
    {
        get { return this.StudentID; }
        set { this.StudentID= value; }
    }
    public Student MyMethod_BLL()
    {
        // return Object of Student Type;
    }
   }
}

现在在我的App.Project中,我想访问Student类型的对象来序列化它,并使用webservice作为JSON返回,但无法正确绑定。我是在多层项目中访问类和对象的新手。

正确引用多层应用程序中的类和类成员

如果需要在web项目中使用Student类,则需要添加对其中定义的程序集的引用。

最佳做法是添加一个名为"App.Entities"或"App.Models"的新层,该层应包含所有业务实体。然后,您将从DAL、BLL和Web项目中添加对它的引用:

  1. 应用实体
  2. App.DAL(参考实体)
  3. App.BLL(参考Entites和DAL)
  4. 应用程序项目(参考实体和BLL,但不直接参考DAL)

使用这种方法,您将消除从Web项目中引用DAL的必要性,因此Web应用程序知道将接收学生对象,但不知道学生来自数据库、Web服务或其他数据提供商。

为什么要创建两次Student类,一次在DAL中,另一次在BLL中。实际上,它是业务对象类,应该从DAL和BLL方法中移动实际上,您需要为业务对象(实体/模型)创建新项目

在所有DAL、BLL和web项目中添加BO项目的参考。在BLL中添加DAL的参考和在web项目中添加BLL的参考。从web项目中,调用BLL类的所有方法来获取或保存数据库中的数据。

例如,学生商务舱会像:

public class Student
{
   public int StudentId { get; set; }
   public string FirstName { get; set; }
   public string MiddleName { get; set; }
}

DAL类将类似

public class StudentDAL
{
   public List<Student> GetAll()
   {
     -----
   }
   public Student GetById(long studentId)
   {
     -----
   }
}

您可以在BLL类中创建静态方法,如

public class StudentBLL
{
   public static List<Student> GetAll()
   {
     using (StudentDAL studentDAL = new StudentDAL())
     {
         return studentDAL.GetAll();
     }
   }
   public static Student GetById(long studentId)
   {
      using (StudentDAL studentDAL = new StudentDAL())
     {
        return studentDAL.GetById(studentId);
     }
   }
}

从网络上,你可以通过进行调用

List<Student> studentList = StudentBLL.GetAll();