我正在尝试使用将 a 添加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);
}