EF 查询数据

版权声明:本文为博主原创文章,未经博主允许不得转载,如果转载请写明出处。 https://blog.csdn.net/w200221626/article/details/51969387



点击确定添加后自动生成Model1.cs

    public partial class Model1 : DbContext
    {
        public Model1()
            : base("name=Model11")
        {
        }

        public virtual DbSet<AreaInfo> AreaInfo { get; set; }
        public virtual DbSet<UserInfo> UserInfo { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AreaInfo>()
                .Property(e => e.Address)
                .IsUnicode(false);

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.Name)
                .IsFixedLength();

            modelBuilder.Entity<UserInfo>()
                .Property(e => e.Jg)
                .IsFixedLength();
        }
    }

UserInfo.cs自动生成如下

    [Table("UserInfo")]
    public partial class UserInfo
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public int Age { get; set; }

        [StringLength(10)]
        public string Jg { get; set; }
    }
EF 查询一

        public void GetInfo()
        {
            richTextBox1.Text = string.Empty;
            using (Model1 db = new Model1())
            {
                //1.Linq to Entities
                var info = from c in db.UserInfo where c.Age > 10 orderby c.Age descending  select c;
                foreach (var item in info)
                {
                    richTextBox1.Text += "姓名:" + item.Name + " 年龄:" + item.Age + "\n";
                }
            }
        }


EF 查询数据二

               //2.Lambda查询
                var info = db.UserInfo.Where(c => c.Age > 10).OrderBy(c => c.Age);

EF 查询数据三

//3.ObjectContext.CreateQuery查询
var sql = "select value a from UserInfo as a  where a.Age > 20 order by a.Age desc limit 10";
var info = ((IObjectContextAdapter)db).ObjectContext.CreateQuery<UserInfo>(sql);


EF 查询数据四

//4.SqlQuery<>查询
var sql = "select * from UserInfo where age > 15 order by age desc";
var info = db.Database.SqlQuery<UserInfo>(sql);
这样用*查询的是全部列的数据

如果我只查询两列Name和Age怎么办

精简UserInfo

class User
{
      public string Name { get; set; }
      public int Age { get; set; }
}

var sql = "select Name,Age from UserInfo where age > 15 order by age desc";
var info = db.Database.SqlQuery<User>(sql);


两个的查询结果相同


EF 查询数据五

//5.SqlQuery()查询
var sql = "select * from UserInfo where age > 15 order by age desc";
object[] obj = new object[1];
var info = db.UserInfo.SqlQuery(sql, obj);
查询结果和四相同



展开阅读全文

没有更多推荐了,返回首页