alh*_*hpe 4 c# entity-framework
我想删除拆分为两个实体的表行。
如果我尝试删除主要实体,那么在不使用context.Entry(...).Reference.. 加载相关其他实体之前会收到错误消息。
在我要删除整行之前,检索相关实体有点傻吗?
如果我继续评论该context.Entry(...) 行,则会收到以下错误
遇到无效的数据。缺少必需的关系。检查状态条目以确定违反约束的来源。
我在下面添加代码。能否请某人帮助我删除拆分的实体,而不必之前“加载”相关的实体?
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是使用存根实体:仅具有ID值的实体对象:
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();
Run Code Online (Sandbox Code Playgroud)
如果您知道一个ProductID,甚至可以通过仅创建两个存根来删除Product和ProductPhoto。
| 归档时间: |
|
| 查看次数: |
1226 次 |
| 最近记录: |