ef core如何能像ef一样使用add等方法
时间: 2024-01-20 07:03:04 浏览: 40
在EF Core中,您可以使用以下命令来添加实体:
1. 使用`DbContext.Set<TEntity>()`方法获取实体的DbSet并添加实体对象,例如:
```csharp
var context = new YourDbContext();
var newEntity = new YourEntity { Property1 = "value1", Property2 = 2 };
context.Set<YourEntity>().Add(newEntity);
context.SaveChanges();
```
2. 直接在DbContext中添加实体对象,例如:
```csharp
var context = new YourDbContext();
var newEntity = new YourEntity { Property1 = "value1", Property2 = 2 };
context.Add(newEntity);
context.SaveChanges();
```
3. 使用`DbContext.Entry<TEntity>(TEntity)`方法获取实体的DbEntityEntry并添加实体对象,例如:
```csharp
var context = new YourDbContext();
var newEntity = new YourEntity { Property1 = "value1", Property2 = 2 };
context.Entry(newEntity).State = EntityState.Added;
context.SaveChanges();
```
以上三种方法都可以实现向数据库中添加实体对象的操作,您可以根据自己的需求选择其中一种方法来使用。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)