添加新记录需要检查它是否存在与实体框架存储库模式



我正在使用实体框架存储库模式。现在我想添加新记录。

if (question != null)
{
var clq = new CountryLanguageQuestion
{
CountryId = s.CountryId,
LanguageId = languageId,
QuestionNumber = questionNum,
SurveyQuestionId = s.SurveyQuestionId,
QuestionText = s.QuestionText
};
_countryLanguageQuestionRepository.Add(clq);
_unitOfWork.Commit();
}

上述代码的问题是添加记录而不检查它是否存在。在表中,有一个标识列。CountryId、LanguageId 和 SurveyQuestionId 可以为空。我们的存储库类继承了基类。

public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
T GetById(long Id);
T GetById(string Id);
T Get(Expression<Func<T, bool>> where);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
IQueryable<T> GetQueryable(Expression<Func<T, bool>> where);
}

那么如何在添加新记录之前检查记录是否存在呢?

你可以尝试这样的事情:

//Find it however you can in the context
var existing = _countryLanguageQuestionRepository.GetById(id);
if (existing == null){
var clq = new CountryLanguageQuestion
{
CountryId = s.CountryId,
LanguageId = languageId,
QuestionNumber = questionNum,
SurveyQuestionId = s.SurveyQuestionId,
QuestionText = s.QuestionText
};
_countryLanguageQuestionRepository.Add(clq);
} else {
//Update existing object and save it
}

最新更新