.net framework ef封装类,增删改查,批量新增,批量删除,批量修改,支持内连接,请封装好给出源码
时间: 2024-10-24 15:05:15 浏览: 12
.NET Framework 的 Entity Framework (EF) 是一个强大的ORM(对象关系映射)库,它允许开发者通过代码操作数据库,而无需直接编写SQL语句。下面是一个基本的Entity Framework的CRUD(创建、读取、更新、删除)以及批量操作的示例,这是在一个基于`DbContext`的类中的简单封装。假设我们有一个名为`MyEntities`的上下文类,并且有`Customer`实体:
```csharp
using System.Data.Entity;
using System.Collections.Generic;
public class MyEntities : DbContext
{
public DbSet<Customer> Customers { get; set; }
// CRUD operations
public Customer CreateCustomer(Customer customer)
{
return Customers.Add(customer).Entity;
}
public Customer GetCustomer(int id)
{
return Customers.Find(id);
}
public void UpdateCustomer(Customer customer)
{
Customers.Attach(customer);
Customers.Update(customer);
}
public void DeleteCustomer(Customer customer)
{
Customers.Remove(customer);
}
// Batch operations
public int BulkSaveChanges(IEnumerable<Customer> customers)
{
return SaveChanges();
}
// Inner join example
public List<Customer> GetCustomersWithOrders(int customerId)
{
var query = from c in Customers
join o in Orders on c.Id equals o.CustomerId
where c.Id == customerId
select c;
return query.ToList();
}
}
// Customer entity
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
// Other properties...
}
// Assuming there's also a `Orders` DbSet for the example.
```
这个例子展示了如何对`Customer`对象进行CRUD操作,以及如何利用`DbContext`的特性来进行批量保存更改。对于复杂的查询,如内连接,可以使用LINQ查询语法。
阅读全文