我使用 EF 作为 ORM,但我在使用外键进行简单添加对象时遇到问题。我在下面执行此代码以将新文章添加到 DB。
dataLayer = new CmsDataLayer();
var newArticle = new Article();
newArticle.Author = AuthorService.CurrentAuthor; //id =8
dataLayer.Articles.Insert(newArticle);
有CmsDataLayer.ICmsRepository
存储库模式(简单的 CRUD 操作)
class CmsDataLayer
{
public ICmsRepository<Author> Authors = new MsSqlServerCmsRepository<Author>();
}
在方法插入我这样做
class MsSqlServerCmsRepository
{
private DbSet<T> dataSet;
public MsSqlServerCmsRepository()
{
dataSet = dataContext.Set<T>();
}
public void Insert(T entity)
{
this.dataSet.Add(entity);
this.dataContext.SaveChanges(); //<--
}
在此操作newArticle.Author
获得作者 ID 的新值后,在SaveChanges()
实体之前它有 Author with id=8
,在 Author 之后有id=14
。
我不明白为什么AuthorId
保存操作后EF更改,id = 8的作者存在w DB?