C# 如何在EF 5中以1对1关系保存两个表中的记录
因此,我正在从事这个C# 如何在EF 5中以1对1关系保存两个表中的记录,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,因此,我正在从事这个ASP.netmvc4项目,到了这个地步,我觉得我无法解决这个问题。我正在使用实体框架5和代码优先工作流。我有这两个实体: public class Document { public int DocumentID { get; set; } public string Name { get; set; } public string Description public int UserFileID { get; set; } pub
ASP.netmvc4
项目,到了这个地步,我觉得我无法解决这个问题。我正在使用实体框架5
和代码优先
工作流。我有这两个实体:
public class Document
{
public int DocumentID { get; set; }
public string Name { get; set; }
public string Description
public int UserFileID { get; set; }
public UserFile UserFile { get; set; }
}
及
public class UserFile
{
public int UserFileID { get; set; }
public string FileName { get; set; }
}
现在我有了一个管理员部分,允许管理员创建新的文档
,大多数时候用户会想向文档中添加某种文件,但我想单独管理用户上传的文件,因此我有一个明确的实体,我计划在其中存储所有上传的文件
有些东西看起来很标准,但我真的搞不懂是这样的:
我有一张表格:
@using (Html.BeginForm("Documents", "Admin",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.Name)
@Html.TextBoxFor(m => m.Description)
<input name="file" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
但是,我必须保存文档
,在那里我可以重新开始:
Document entity = new Document();
entity.Name = model.Name;
entity.Description = model.Description;
entity.UserFile = ???
unitOfWork.DocumentRepository.Add(entity);
我真正不知道的是如何处理外键。我有一点经验,但据我记忆,在其他场景中,我只需要传递类型为UserFile
的对象,比如:
var entityUserFile = unitOfWork.UserFileRepository.GetById(Id);
然后:
entity.UserFile = entityUserFile;
但我看不到在UserFile
表中获取新创建记录的ID的方法。我可以通过为每个文件设置唯一的名称来考虑解决方法,但我想知道是否有一些方法可以解决这个问题。可能是某种code-First
方法,在这种方法中,我可以创建两个实体实例,并让实体框架处理关系的设置,可能是其他方法?或者我有义务保存用户文件
实体,然后将其取回并作为我的文档
实体的值传递?您尝试过这个吗
UserFile item = new UserFile();
Document entity = new Document();
entity.Name = model.Name;
entity.Description = model.Description;
entity.UserFile = item;
unitOfWork.DocumentRepository.Add(entity);
unitOfWork.SaveChanges();
DbSet.Add()
参考:
或者,EF应该在保存更改()时修复您的ID。因此,这也应该起作用:
UserFile item = new UserFile();
unitOfWork.UserFileRepository.Add(item);
unitOfWork.SaveChanges();//Database generates key
//and EF fixes its in-memory version
Document entity = new Document();
entity.Name = model.Name;
entity.Description = model.Description;
entity.UserFileID = item.ID; //use the foreign key to avoid duplicate
unitOfWork.DocumentRepository.Add(entity);
unitOfWork.SaveChanges();
您可能希望将其包含在TransactionScope
中,因为现在有两个调用SaveChanges()
事实上,在我写完本文后,我尝试了您的建议,只是添加了item.FileName=“SomeName”代码>而且似乎有效。事实上,我在两个表中都有记录,所以它是有效的,但我不完全确定这是否是正确的方法。你认为应该这样做吗?我不知道为什么,但我不喜欢这种方法…另一个版本补充说,你可能更喜欢谢谢你的回答。我担心我完全走错了方向,我不能说一个更好,也许如果你或其他人能说哪一个更好用
UserFile item = new UserFile();
unitOfWork.UserFileRepository.Add(item);
unitOfWork.SaveChanges();//Database generates key
//and EF fixes its in-memory version
Document entity = new Document();
entity.Name = model.Name;
entity.Description = model.Description;
entity.UserFileID = item.ID; //use the foreign key to avoid duplicate
unitOfWork.DocumentRepository.Add(entity);
unitOfWork.SaveChanges();