1

假设我有一个Car界面。每个Car都有一组零件作为ICollection<Part>。除了类引用之外,该Part实体还有一个 ID 和一个可选的外键引用。CarIdPublic Car Car{ get; set;}

所以这是有趣的部分。假设我有一个按Part ID. 我Part通过访问存储库来提供表格 a 。form.Part = repos.Retrieve(PartID). 现在表单具有对零件的引用(以及零件通过零件所属的车辆)。我通过使用创建表单context.Forms.Add(form);

数据库创建了一个DUPLICATE车辆和零件,具有自己的单独 ID,而不是引用已经存在的 ID。

有人可以解释为什么会这样吗?


编辑

想要它们的人的类示例:

public class Form
{
    public int ID { get; set;}

    public Part Part { get; set;}      // Reference to Part
    public int? PartId { get; set; }   // Foreign Key to Part ID
}

public class Car : Vehicle
{
    public int ID { get; set;}

    public virtual ICollection<Part> Parts { get; set;} //Each car has parts
}

public class Part
{
    public int ID { get; set;}

    public Car Car { get; set;}      // Reference to Car
    public int? CarId { get; set; }   // Foreign Key to Car
}

将导致此故障的代码。假设 Part 和 Car 已经存在于数据库中:

form Form = new form();
form.Part = partRepository.Retrieve(5); //gets part with id = 5
context.formRepository.Add(form); // new part created, duplicate of part #5 but with the next available id.
4

2 回答 2

3

在这些存储库中的某个地方,您有一个DbContext用于与数据库通信,对吗?

问题是您正在Parts通过两个不同的存储库处理同一个实体 (the )。当您将表单添加到表单存储库时,它可能会使用它。该存储库无法知道这些部分已经存在于数据库中并且是从数据库加载的,因为它们来自另一个存储库/DbContext。

You should really redesign your system so that those repositories either share a common DbContext when used together, or you should make just one repository instead of two.

(Personally I've never understood why people are always creating repositories on top of entity framework. The DbContext is an implementation of the repository pattern itself).

于 2012-07-31T20:40:00.573 回答
0

请尝试使用 Data Annotation Key Attribute 标记您的 Id.s,这会将它们标记为主键以避免重复

public class Form
{
    [Key]
    public int ID { get; set;}

    public Part Part { get; set;}      // Reference to Part
    public int? PartId { get; set; }   // Foreign Key to Part ID
}

public class Car : Vehicle
{
    [Key]
    public int ID { get; set;}

    public virtual ICollection<Part> Parts { get; set;} //Each car has parts
}

public class Part
{
    [Key]
    public int ID { get; set;}

    public Car Car { get; set;}      // Reference to Car
    public int? CarId { get; set; }   // Foreign Key to Car
}
于 2012-07-31T20:39:46.763 回答