使用EF5.0查询数据库

使用EF5.0查询数据库

开发环境:VS2010

开发语言:C#

实现功能:从数据库查询结果

方法1,Linq To Entity表达式:

//eg1-1:查询到新建对象
List list =
( 
  
from d in db.DeviceInfoes
    where d.DevID == deviceID
    select new DeviceLocation 
    { DevID = d.DevID, PosLng = d.PosLng, PosLat = d.PosLat }

).ToList();

//eg1-2:遍历打印内容
using (var db = new AdventureWorksContext())
{
    var persons = from p in db.People
                    where p.LastName == "Stevens"
                    orderby p.FirstName
                    select p;

    foreach (var p in persons)
    {
        Console.WriteLine("FirstName:{0},LastName:{1}", p.FirstName, p.LastName);
    }
}

方法2,EF方法:

//eg2-1:多条件查询
var list = db.DeviceInfoes
            .Where(p => p.DevID == deviceID && p.DevTime>='2019-01-01')
            .FirstOrDefault();
//eg2-2:新增条目
using (var db = new AdventureWorksContext())
{
	var stephen = new Person 
	{ 
		BusinessEntityID=20778,
		PersonType="EM",
		NameStyle=false,
		Title="Architec",
		FirstName="Stephen",
		LastName="Chow",
		EmailPromotion=1,
		rowguid = Guid.NewGuid(),
		ModifiedDate = DateTime.Now
	};
	db.People.Add(stephen);

	var jeffrey = new Person
	{
		BusinessEntityID = 20779,
		PersonType = "EM",
		NameStyle = false,
		Title = "Engineer",
		FirstName = "Jeffrey",
		LastName = "Lee",
		EmailPromotion = 0,
		rowguid=Guid.NewGuid(),
		ModifiedDate=DateTime.Now
	};
	db.Entry(jeffrey).State = EntityState.Added;

	db.SaveChanges();
}

方法3,原生SQL语句:

//eg:3-1:查询并遍历结果
using (var db = new AdventureWorksContext())
{
    var persons = db.People.SqlQuery("SELECT * FROM Person.Person WHERE LastName='Stevens'");

    foreach (var p in persons)
    {
        Console.WriteLine("FirstName:{0},LastName:{1}", p.FirstName, p.LastName);
    }
}

//eg3-2:非实体查询
using (var db = new AdventureWorksContext())
{
	var persons = db.Database.SqlQuery("SELECT FirstName FROM Person.Person WHERE LastName='Stevens'").ToList();
	foreach (var p in persons)
	{
		Console.WriteLine("FirstName:{0}", p);
	}
}

//3-3:无返回查询
using (var db = new AdventureWorksContext())
{
	db.Database.ExecuteSqlCommand("UPDATE Person.Person SET NameStyle=1 WHERE BusinessEntityID='1813'");
}

 

2019年,加油!

你可能感兴趣的:(C#,EF5.0)