2

我正在使用 EF Code First 5。我有 3 个实体/POCO 类 - 相关的提案、文档和模板。提案与 Document 表具有 M 到 M 关系。模板与 Document 表具有 M 到 M 的关系。

这是我的 POCO C# 类

public class Document {
   public int Id { get; set; }
   public string FileName { get; set; }
   public ICollection<Proposal> Proposals { get; set; }
   public ICollection<Template> Templates { get; set; }
}

public class Proposal {
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Description { get; set; }
    public ICollection<Document> Documents { get; set; }
}

public class Template {
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Description { get; set; }
    public ICollection<Document> Documents { get; set; }
}

在我的前端 MVC 应用程序中,用户创建一个提案并向其中添加文档。然后我在我的 MVC 操作方法中接收发布的数据并将所有文档添加到提案文档集合中

 proposal.Description = model.Description;
 proposal.Documents = GetDocumentsFromPostedFiles(model.Files);
 db.Entry(proposal).State = EntityState.Added;
 db.SaveChanges();

这可以完美地工作,因为在保存到数据库时文档被分配了唯一的 ID 并链接到我的提案。

然而,在具有相同操作的同一屏幕中,用户可以选择将他添加到提案中的文档保存到新模板中。因此,我希望模板表能够引用在我的一个 MVC 操作方法中添加到提案中的相同文档。我收到发布的数据 - 1 提案。- 许多文档 - 新的模板标题、描述,所以我要更新的是所有 3 个包含此已发布数据的表。

我尝试了以下方法:

 proposal.Description = model.Description;
 proposal.Documents = GetDocumentsFromPostedFiles(model.Files);

 template.Description = model.TemplateDescription;
 template.Documents = proposal.Documents();

 db.Entry(proposal).State = EntityState.Added;
 db.Entry(template).State = EntityState.Added;   

 db.SaveChanges();

这显然更新不正确,因为新的未添加文档未设置文档 ID(默认值为 0),因为数据库将在 db.SaveChanges 之后将其设置在数据库中,因此当我运行它时,模板的文档 ID 被错误保存为 0。

如何告诉实体框架模板对象的文档与刚刚添加的提案文档相关?我使用提案或模板的 1 到 M 的起点来告诉实体框架将它们添加到数据库中,但是在我的情况下,因为我有两个 1 到 M 关系,我如何告诉 EF 这两个 M 表在当我执行初始 db.SaveChanges 时,实际上是同一张表吗?

任何其他可能的解决方案?我只能考虑先将提案保存到数据库中,然后读取所有刚刚添加的文档及其从数据库中创建的主键 ID,然后将它们添加到我的模板中。这将导致再次出现 db.SaveChanges、Linq db Fetch 和 db.SaveChanges,而我宁愿在一个 db.SaveChanges 中执行此操作。

4

1 回答 1

0

SaveChanges()提案初始化后 调用:

proposal.Description = model.Description;
proposal.Documents = GetDocumentsFromPostedFiles(model.Files);

db.Entry(proposal).State = EntityState.Added;
db.SaveChanges();

template.Description = model.TemplateDescription;
template.Documents = proposal.Documents;

db.Entry(template).State = EntityState.Added;   
db.SaveChanges();
于 2013-09-16T14:04:48.460 回答