Я пытаюсь добавить ProfileProperty в таблицу ProfileProperties, используя ObjectContext.AddObject.
Поля db для таблицы ProfileProperties:
ProfilePropertyID
ProfilePropertyDefinitionID
UserID
PropertyValue
Поля db для таблицы ProfilePropertyDefinitions:
ProfilePropertyDefinitionID
PropertyName
Переменные для передаваемого объекта ProfileProperty:
ProfilePropertyID
ProfilePropertyDefinition
User
PropertyValue
И ProfilePropertyDefinitionID, и UserID являются внешними ключами, поэтому после создания объекта ProfileProperty я выбираю User и ProfilePropertyDefinition из их таблиц, чтобы заполнить ProfileProperty связанными объектами.
Затем, когда я пытаюсь AddObject передать объект с этими переменными, я получаю сообщение об ошибке:
InnerException = {"Невозможно вставить значение NULL в столбец 'PropertyName', таблица 'mydbserver.dbo.ProfilePropertyDefinitions'; столбец не допускает пустых значений. Ошибка INSERT.\r\nВыполнение оператора завершено."}
Я сделал перерыв, чтобы проверить, что держит объект, который я передал, и он имеет это:
ProfilePropertyID = -1
ProfilePropertyDefinition =
{ ProfilePropertyDefinitionID = 3
PropertyName = "First Name" }
User = /*Not going to put details here, but assume the user object is there*/
PropertyValue = "Matt"
Вопросы
- Почему говорят, что
PropertyNameравно нулю, когда оно есть? - Почему он вообще пытается добавить объект
ProfilePropertyDefinitionв таблицуProfilePropertyDefinitions? (Я не хочу, чтобы он добавлял или обновлял связанные объекты)
Сервисный уровень AddProfile()
public int AddProfile(ProfilePropertyViewModel property)
{
int objId = -1;
ProfileProperty profile = null;
if (ValidateProfile(property))
{
try
{
using (DbTransaction transaction = _profileRepository.BeginTransaction())
{
profile = ProfilePropertyTranslator.ViewToDomain(property);
profile.User = _userRepository.SelectByKey(UserColumns.UserName, property.UserName);
profile.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("GraffytysDBEntities.ProfilePropertyDefinition", "ProfilePropertyDefinitionID", property.ProfilePropertyDefinitionID);
_profileRepository.Add(profile);
if (_profileRepository.Save() >= 0)
{
transaction.Commit();
objId = property.ProfilePropertyId;
}
}
}
catch(Exception ex)
{
throw ex;
}
}
return objId;
}
Репозиторий Add():
public void Add(E entity)
{
_ctx.AddObject(entity.GetType().Name, entity);
}
ProfilePropertyс существующимиUserиProfilePropertyDefinition. Выбираете ли вы существующие объекты из того же контекста, в котором вы вызываетеAddObject? - person Sander Rijken   schedule 03.01.2010ProfilePropertyDefinitionReference.EntityKeyиUserReference.EntityKey. Вам не нужно будет сначала выбирать его из БД, и это, вероятно, решит вашу проблему. - person LukLed   schedule 03.01.2010