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

时间:2013-12-12 10:48:13

标签: c# asp.net inheritance

我对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. App.Project //引用BLL
  4. 在DAL中,我有一个名为Student

    的公共类
    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返回,但无法正确绑定。我是新访问多层项目中的类和对象。

2 个答案:

答案 0 :(得分:1)

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

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

  1. App.Entities
  2. App.DAL(参考实体)
  3. App.BLL(引用Entites和DAL)
  4. App.Project(引用实体和BLL,但不直接引用DAL)
  5. 使用此方法,您将无需从Web项目引用DAL,因此Web应用程序知道将接收Student对象,但不知道Student来自数据库,Web服务或其他数据提供商。

答案 1 :(得分:0)

为什么要创建Student类2次,一个在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();