EF 查詢資料

鴻雁發表於2016-07-20



點選確定新增後自動生成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);
查詢結果和四相同



相關文章