添加新记录需要检查它是否存在 Entity Framework 存储库模式
Add new record need to check if it exists with Entity Framework repository pattern
我正在使用 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();
}
上面代码的问题是添加记录时没有检查记录是否存在。在 table 中,有一个标识列。 CountryId、LanguageId 和 SurveyQuestionId 可以为空。我们的存储库 class 继承了基础 class.
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
}
我正在使用 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();
}
上面代码的问题是添加记录时没有检查记录是否存在。在 table 中,有一个标识列。 CountryId、LanguageId 和 SurveyQuestionId 可以为空。我们的存储库 class 继承了基础 class.
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
}