I'm trying to add a ProfileProperty
into the ProfileProperties
table using ObjectContext.AddObject
.
The db
fields for the ProfileProperties
table are:
ProfilePropertyID
ProfilePropertyDefinitionID
UserID
PropertyValue
The db
fields for the ProfilePropertyDefinitions
table are:
ProfilePropertyDefinitionID
PropertyName
The variables for the ProfileProperty
object passed in are:
ProfilePropertyID
ProfilePropertyDefinition
User
PropertyValue
The ProfilePropertyDefinitionID
and UserID
both are foreign keys, so after creating the ProfileProperty
object I select the User
and the ProfilePropertyDefinition
from their tables to fill the ProfileProperty
with the related objects.
Then, when I try to AddObject
, passing in an object with those variables I get an error:
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."}
I did a break to check to see what the object I passed in was holding and it has this:
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
is null when it's there? ProfilePropertyDefinition
object into the ProfilePropertyDefinitions
table in the first place? (I don't want it to add or update related objects)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);
}
This will propably solve your problem and is more efficient way to set foreign key properties:
profileProperty.ProfilePropertyDefinitionReference.EntityKey = new EntityKey("MyEntities.ProfilePropertyDefinitions", "ProfilePropertyDefinitionID", 3);
You have to replace 'MyEntities' with your db model name.
You could also check if you are adding ProfilePropertyDefinition
to your ObjectContext
somewhere else in the code. It could be the problem, not this part of the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With