删除在多个实体上拆分的表行时出错 [英] Error deleting a table row splitted on multiple entities
问题描述
我要删除拆分为两个实体的表行。
I want to delete a table row that is split on two entities.
如果我尝试删除主实体,如果在不这样做之前会收到错误消息t使用 context.Entry(...)。Reference
..
If I try to delete the main entity, I get an error if before I don't load the related other entity using context.Entry(...).Reference
..
加载相关的其他实体在我要删除整行之前傻傻地检索相关实体吗?
Is a bit silly to retrieve the related entities before, when I am going to delete the full row?
如果我继续评论上下文,则会出现以下错误.Entry(...)
行
遇到无效数据。缺少必要的关系。检查
状态条目以确定约束违反的来源。
Invalid data encountered. A required relationship is missing. Examine State Entries to determine the source of the constraint violation.
我添加以下代码。
using System.Data.Entity;
using System.Linq;
namespace Split
{
class Program
{
static void Main(string[] args)
{
using (var context = new DataContext())
{
var product = new Product()
{
Name = "my Article",
Photo = new ProductPhoto() { PhotoUrl = "http://myfoto.jpg" }
};
context.Products.Add(product);
context.SaveChanges();
}
using (var context = new DataContext())
{
var product = context.Products.First();
//context.Entry(product).Reference(e => e.Photo).Load();
context.Products.Remove(product);
context.SaveChanges();
}
}
}
class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ProductPhoto Photo { get; set; }
}
class ProductPhoto
{
public virtual int ProductId { get; set; }
public virtual string PhotoUrl { get; set; }
public virtual Product Product { get; set; }
}
class DataContext : DbContext
{
public DataContext()
: base("name=DefaultConnection")
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Product> Products { get; set; }
public DbSet<ProductPhoto> ProductPhotos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.ToTable("Products")
.HasKey(e => e.Id)
.HasRequired(e => e.Photo)
.WithRequiredPrincipal(e => e.Product);
modelBuilder.Entity<ProductPhoto>()
.ToTable("Products")
.HasKey(e => e.ProductId);
base.OnModelCreating(modelBuilder);
}
}
}
推荐答案
执行此操作的最佳方法是使用 stub实体:仅具有ID值的实体对象:
The best way to do this is by using a stub entity: an entity object that's only got an Id value:
var product = context.Products.First();
var photo = new ProductPhoto { ProductId = product.ProductId }; // Stub
context.Entry(photo).State = System.Data.Entity.EntityState.Deleted;
context.Products.Remove(product);
context.SaveChanges();
如果您知道产品
的ID您甚至可以仅创建两个存根就可以删除 Product
及其 ProductPhoto
。
If you know a Product
's Id you can even delete both the Product
and its ProductPhoto
by only creating two stubs.
这篇关于删除在多个实体上拆分的表行时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!