我正在尝试使用 ObjectContext.AddObject
将 ProfileProperty
添加到 ProfileProperties
表中。
ProfileProperties
表的 db
字段是:
ProfilePropertyID
ProfilePropertyDefinitionID
UserID
PropertyValue
ProfilePropertyDefinitions
表的 db
字段是:
ProfilePropertyDefinitionID
PropertyName
传入的 ProfileProperty
对象的变量是:
ProfilePropertyID
ProfilePropertyDefinition
User
PropertyValue
ProfilePropertyDefinitionID
和 UserID
都是外键,所以在创建 ProfileProperty
对象后,我选择了 User
和它们表中的 ProfilePropertyDefinition
以使用相关对象填充 ProfileProperty
。
然后,当我尝试 AddObject
时,传入一个带有这些变量的对象时,我得到一个错误:
InnerException = {"Cannot insert the value NULL into column 'PropertyName', table 'mydbserver.dbo.ProfilePropertyDefinitions'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
我休息了一下,检查我传入的对象持有什么,它有这个:
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.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("MyEntities.ProfilePropertyDefinitions", "ProfilePropertyDefinitionID", 3);
您必须将“MyEntities”替换为您的数据库模型名称。
您还可以检查您是否在代码的其他地方将 ProfilePropertyDefinition
添加到您的 ObjectContext
。这可能是问题所在,而不是这部分代码。
关于c# - 遇到 Entity Framework 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1995878/