WCF与Entity Framework Code First

3

我希望在我的WCF服务中使用EF来获取数据并将其显示给客户端。 我需要以下建议:

  1. Do I need to have the same interface for all the views (e.g. students, teachers etc.) or do I need to have a different interface and service for every table (or view)

  2. Do I need to generate the database calls within my service (.svc) or some other architecture is preferred?

    public Student[] GetAllStudents()
    {
       //database generation code here
    }
    
  3. How can I use EF code-first approach to generate database. I know that for an MVC app, you need to set the initializer in Global.asax or in web.config but I am not sure how it's called in this case. My model looks like this:

    [DataContract]
    public class Student
    {
        [DataMember]
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [DataMember]
        public string Type { get; set; }
        [DataMember]
        public string Subject { get; set; }
        [DataMember]
        public string Description { get; set; }
    }
    

  1. 不,你可以这样做,会让事情更加清晰;
  2. 嗯,也许 OData 可以在这里发挥作用?
  3. 听起来你可能会从教程文章中受益,而不是从 SO 上找答案。
- user585968
1个回答

0
你真正应该做的是将系统分解成更多独立的层。不要直接查询数据库,而是创建一个“业务逻辑”层,将WCF调用提供的信息转换为EF调用所需的信息。这被称为N-Tier应用程序
public class SchoolAPI : ISchoolAPI
{
    private DataAccessLayer _dal = new DataAccessLayer();

    public Student[] GetAllStudents()
    {
        return _dal.GetStudents(null, null);
    }

    public Student[] GetAllScienceStudents()
    {
        return _dal.GetStudents(null, DataAccessLayer.ScienceStudentType);
    }
}

private class DataAccessLayer
{
    public static readonly ScienceStudentType = //...

    public Student[] GetStudents(string subject, string type)
    {
        using(var ctx = new SchoolContext())
        {
            IQueryable<Student> studentQuery = ctx.Students;

            if(subject != null)
                studentQuery = studentQuery.Where(s=>s.Subject == subject);

            if(type != null)
                studentQuery = studentQuery.Where(s=>s.Type == type);

            return studentQuery.ToArray();
        }
    }
}

WCF调用者不需要知道字符串ScienceStudentType是什么,它只关心它能获取到科学生。通过将业务逻辑与数据库调用分离,您的服务调用者不再需要了解这些。

对于EF,它会在框架第一次“触及”数据库并检测到不存在时进行初始化(如果设置为这样)。这是在SchoolContext的构造函数中完成的,但对于本答案来说有点太广泛了。我建议找一个EF教程,在没有WCF的简单测试环境中使其正常工作(也许是一个简单的控制台应用程序,只需调用GetStudents()),然后将其移植到WCF环境中。


这是否意味着:1)首先创建一个基于MVC的解决方案,2)生成数据库,如果一切正常,3)在解决方案中添加WCF应用程序项目,4)通过将其引用添加到WCF项目中调用基于MVC的DAL层,5)删除控制器和视图,因为它们不是必需的。如有需要,请纠正我。 - newbie
使用3个项目,1)一个完全独立于使用它的内容的DAL dll。2)一个“沙盒项目”,包括从#1引用的项目,以使其运行起来。这可以是控制台应用程序、MVC Web应用程序或任何其他东西,它只是临时的,直到您通过EF解决了问题。3)您的WCF项目也使用#1中的DLL。 - Scott Chamberlain
谢谢@Scott Chamberlain 最后一个建议。 1)我能否从相同的接口即ISchool继承我的DAL,该接口也用于我的WCF服务? 2)如果我必须在我的WebService中定义多个方法,例如从IStudent获取学生方法,从ITeacher获取教师方法怎么办? 提前致谢。 - newbie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接