ASP.NET中使用Entity Framework(EF)基本操作
原创
©著作权归作者所有:来自51CTO博客作者我有一个想法的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 创建数据库上下文(DbContext)类:
using System.Data.Entity;
public class MyDbContext : DbContext
{
public MyDbContext() : base("MyDbContext")
{
}
public DbSet<MyEntity> MyEntities { get; set; }
}
- 创建实体类:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
- 在Web.config中配置数据库连接字符串:
<connectionStrings>
<add name="MyDbContext" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
- 添加新的数据:
using (var context = new MyDbContext())
{
var entity = new MyEntity { Name = "John" };
context.MyEntities.Add(entity);
context.SaveChanges();
}
- 查询数据:
using (var context = new MyDbContext())
{
var entities = context.MyEntities.ToList();
foreach (var entity in entities)
{
Console.WriteLine(entity.Name);
}
}
- 更新数据:
using (var context = new MyDbContext())
{
var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);
if (entity != null)
{
entity.Name = "Jane";
context.SaveChanges();
}
}
- 删除数据:
using (var context = new MyDbContext())
{
var entity = context.MyEntities.FirstOrDefault(e => e.Id == 1);
if (entity != null)
{
context.MyEntities.Remove(entity);
context.SaveChanges();
}
}