我正在使用Entity Framework存储库模式。现在我要添加新记录。
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可以为null。我们的存储库类继承了基类。
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);
}
那么在添加新记录之前如何检查记录是否存在?
答案 0 :(得分:0)
您可以尝试以下内容:
//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
}