如何从Raw SQL重写为LINQ?

时间:2016-03-06 19:39:36

标签: c# mysql entity-framework linq rawsql

我想用LINQ替换我的Raw SQL。这是我的代码:

myController的:

        using MyProject.Models;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web.Http;

        namespace MyProject.Controllers
        {
            public class MyController : ApiController
            {
                [HttpGet]
                public List<User> UserData()
                {
                    var selUserData = "SELECT * FROM mydb.User";

                    using (var ctx = new ApplicationDbContext())
                    {
                        var userData = ctx.Database.SqlQuery<User>(selUserData).ToList();

                        return userData;                        
                    }
                }

                public class User
                {
                    public int Id { get; set; }
                    public string Username { get; set; }
                    public string Password { get; set; }
                }
            }
        }

的Web.config:

<connectionStrings>
    <add name="MyEntities" providerName="MySql.Data.MySqlClient" connectionString="server=127.0.0.1;port=3306;database=,mydb;uid=root;password=mypass" />
</connectionStrings>

ApplicationDBContext.cs:

    using MySql.Data.Entity;
    using System.Data.Entity;

    namespace MyProject.Models
    {
        [DbConfigurationType(typeof(MySqlEFConfiguration))]
        public class ApplicationDbContext : DbContext
        {
            public ApplicationDbContext() : base(nameOrConnectionString: "MyEntities") { }
        }
    }

我在网上搜索了几天试图寻找解决方案,但没有运气。我的代码应该像var userData = ctx...这样只是添加几行LINQ语法,还是我做错了?我读到LINQ与MySQL不完全兼容。如果我使用MSSQL,我的代码会是什么样子?如果我使用MySQL会是什么样子?

编辑:

UserDAL.cs:

public class UserDAL
{
    public static List<User> UserData()
    {
        using (var ctx = new MyEntities())
        {                
            var userData = ctx.Users.ToList();

            return userData;
        }
    }
}

MyModel.Context.cs(自动生成的代码):

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public partial class MyEntities : DbContext
{
    public SloRideEntities()
        : base("name=MyEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<User> Users { get; set; }
    public virtual DbSet<Ride> Rides { get; set; }
}

User.cs(自动生成的代码):

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.Rides = new HashSet<Ride>();
    }

    public long Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Ride> Rides { get; set; }
}

2 个答案:

答案 0 :(得分:0)

您必须向上下文类

添加DbSet<User>
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() : base(nameOrConnectionString: "MyEntities") { }
    public virtual DbSet<Users> Users { get; set; }
}

然后你写

var userData = ctx.Users.ToList();

答案 1 :(得分:-1)

假设ApplicationDbContext是由Entity Framework T4模板基于您的实体模型(edmx文件,数据库第一种方法)生成的类,并且您已将mydb.User包含在模型中 - 那么您的ApplicationDbContext类应该具有名为User的属性( s)这将是用户的集合。 所以你会有类似下面的内容

using (var ctx = new ApplicationDbContext())
{
     return ctx.Users.ToList();                       
}