Pau*_*aul 30 .net entity-framework entity-framework-4.1
我想知道如何在不首先从数据库加载对象的情况下从Entity Framework 4.1中删除对象.我发现这些 其他的堆栈溢出2个回答,但他们不属于EF 4.1
我尝试了以下代码,但它不起作用
public void DeleteCar(int carId)
{
var car = new Car() { Id = carId };
_dbContext.Cars.Attach(car);
_dbContext.Cars.Remove(car);
_dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我想避免下面的代码.
public void DeleteCar(int carId)
{
var car = context.Cars.Find(carId);
_dbContext.Cars.Remove(car);
_dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我不想调用存储过程或执行原始sql.
agr*_*adl 40
我使用以下内容进行删除,效果很好.
public virtual ActionResult Delete(int commentID)
{
var c = new Comment(){CommentID = commentID};
db.Entry(c).State= EntityState.Deleted;
db.SaveChanges();
return RedirectToAction(MVC.Blog.AdminComment.Index());
}
Run Code Online (Sandbox Code Playgroud)

Sla*_*uma 10
只是为了说服你,你的第一个代码片段必须在这里工作,这是一个简单的例子,你可以复制,粘贴和测试:
EntityFramework.dll(EF 4.1)的引用Program.cs并粘贴:- >
using System.Data.Entity;
namespace EFDeleteTest
{
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Car> Cars { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Database with name "EFDeleteTest.MyContext"
// will be created automatically in SQL Server Express
int carId = 0;
using (var context = new MyContext())
{
var car = new Car { Name = "Test" };
context.Cars.Add(car);
context.SaveChanges();
carId = car.Id;
}
//Make breakpoint here and check that the car is indeed in the DB
using (var context = new MyContext())
{
var car = new Car() { Id = carId };
context.Cars.Attach(car);
context.Cars.Remove(car);
context.SaveChanges();
}
//Make breakpoint here and check that the car
//indeed has been deleted from DB
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有SQL Server Express DB,它将自动创建数据库.
也许这可能有助于您与代码进行比较,因为它看起来好像在您的代码片段中看不到的东西导致您描述的不同行为.
使用存根实体:
public void DeleteCar(int carId)
{
var car = new Car() { Id = carId };
_dbContext.AttachTo("Cars",car);
_dbContext.DeleteObject(car);
_dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
参考:
| 归档时间: |
|
| 查看次数: |
26167 次 |
| 最近记录: |