输出sql语句
using (textEntities entities = new textEntities())
{
entities.Database.Log += c => Console.WriteLine($"SQL: {c}");
}
添加删除
User userNew = new User()
{
Account = "Admin",
Email = "1234567@qq.com",
Password = "12356789"
};
context.Users.Add(userNew);
context.SaveChanges();
context.Users.Remove(userNew);
context.SaveChanges();
context.Entry<User>(userNew).Property<string>("Name").IsModified = true;
context.SaveChanges();
使用SQL语句查询
using (textEntities dbContext = new JDDbContext())
{
{
DbContextTransaction trans = null;
try
{
trans = dbContext.Database.BeginTransaction();
string sql = "Update [User] Set Name='小新' WHERE Id=@Id";
SqlParameter parameter = new SqlParameter("@Id", 1);
dbContext.Database.ExecuteSqlCommand(sql, parameter);
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw ex;
}
finally
{
trans.Dispose();
}
}
{
DbContextTransaction trans = null;
try
{
trans = dbContext.Database.BeginTransaction();
string sql = "SELECT * FROM [User] WHERE Id=@Id";
SqlParameter parameter = new SqlParameter("@Id", 1);
List<User> userList = dbContext.Database.SqlQuery<User>(sql, parameter).ToList<User>();
trans.Commit();
}
catch (Exception ex)
{
if (trans != null)
trans.Rollback();
throw ex;
}
finally
{
trans.Dispose();
}
}
}
监控对象/追踪数据
User userNew = new User()
{
Account = "Admin",
Email = "1234567@qq.com",
Password = "12356789"
};
using (textEntities context= new textEntities())
{
context.Users.Attach(userNew);
userNew = context.Users.Find(userNew.Id);
}
导航属性
var companyList = context.Set<Company>().Include("Users").Where(c => c.Id > 0);
foreach (var company in companyList)
{
Console.WriteLine("Company id={0} name={1}", company.Id, company.Name);
foreach (var item in company.Users)
{
Console.WriteLine("User name={0}", item.Name);
}
}