【问题标题】:EFCode First: Deleting a Value Object with Two Entity AssociationsEFCode First:删除具有两个实体关联的值对象
【发布时间】:2011-05-11 22:26:41
【问题描述】:

我无法从我的数据库中删除一个值对象,因为它与不同的实体有两个关系,它只是将一个外键设置为 null,这会引发。这是我的域名:

public class Product : IEntity
{
    public int Id { get; set; }
    public string ModelNumber { get; set; }
    public ICollection<ProductQuantity> ProductQuantities { get; set; }
}

public class Project: IEntity
{
    public int Id { get; set; }
    public string SpecConnect { get; set; }
    public virtual ICollection<ProductQuantity> ProductQuantitys { get; set; }
}

public class ProductQuantity
{
    public int Id { get; set; }
    public virtual Product Product { get; set; }
    public virtual Project Project { get; set; }
}

这是我从项目中删除 ProductQuantity 的代码:

var product = _productRepository.GetById(id);
var project = _projectRepository.GetById(projectId);
var productQuantity = project.ProductQuantitys.SingleOrDefault(x => x.Product == product);

project.ProductQuantitys.Remove(productQuantity);

感谢您的任何想法!

【问题讨论】:

    标签: ef-code-first entity-framework-4.1


    【解决方案1】:

    这还不够。您必须从ProductProject 中删除该对象,然后您必须通过调用context.ProductQuantities.Remove(...) 删除它

    从这些集合中删除对象只会删除您定义的独立关联。它导致将数据库中的 FK 设置为 null 但不会删除相关对象。

    顺便说一句。值对象没有 ID / 键。 EF 中的值对象是复杂类型。

    【讨论】:

    • 嗨。感谢您的反馈意见。你是对的,我的 ProductQuantity 对象中不应该有 Id。 context.ProductQuantities.Remove 将不起作用,因为此对象不是实体。我想我的域模型错了?我需要有一个 ProductQuantity,因为我在对象中也有一个 Quantity 的整数,所以它不仅仅是项目和产品之间的关联。当我删除 Id 并重建数据库时,我收到一个未设置键的错误,但是当我创建一个映射对象以将 HasKey 属性设置为 Product 和 Project 时,我也收到一个错误?思考正确的方法。
    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多