EntityDataModel set parent key to null on insert or update
I am working in asp.net 3.5 sp1. I have two tables
User
UserID PK (int)
UserName (varchar)
ContactInfoID FK (int) Allow Null
ContactInfo
ConactInfoID PK (int)
Address (varchar)
City (varchar)
State (varchar)
Zip (varchar)
I am trying to use EDM to insert/update a user with no corresponding parent ContactInfo. The database allows for this.
I want to be able to set the ContactInfo_ContactInfoI开发者_C百科D = -1 to represent a null parent. I have the following function in the User partial class. I included the errors I am getting when I tried setting different aspects of the EntityKey to null.
public int ContactInfo_ContactInfoID
{
get
{
if (this.ContactInfoReference == null)
return -1;
if (this.ContactInfoReference.EntityKey == null)
return -1;
return (int)this.ContactInfoReference.EntityKey.EntityKeyValues [0].Value;
}
set
{
//To notify others listening that the property is changing
this.OnPropertyChanging ("ContactInfoReference_ContactInfoD");
if (value != -1)
{
//Always needs to create a new EntityKey object
this.ContactInfoReference.EntityKey =
new EntityKey (
"ProjectRedEntities.ContactInfo",
new EntityKeyMember []
{ new EntityKeyMember("ContactInfoID",
(object)value) });
}
else
{
// this.ContactInfoReference.EntityKey = null;
// ERROR: A relationship is being added or deleted from an AssociationSet 'FK_User_ContactInfo'. With cardinality constraints, a corresponding 'User' must also be added or deleted.
// this.ContactInfoReference.Value = null;
// ERROR : A relationship is being added or deleted from an AssociationSet 'FK_User_ContactInfo'. With cardinality constraints, a corresponding 'User' must also be added or deleted.
// this.ContactInfoReference.EntityKey =
// new EntityKey (
// "ProjectRedEntities.ContactInfo", "ContactInfoID", null);
// ERROR: Value cannot be null.
// this.ContactInfoReference.EntityKey = EntityKey.NoEntitySetKey;
// ERROR: The EntityKey property cannot be set to EntityNotValidKey, NoEntitySetKey, or a temporary key.
// this.ContactInfoReference.EntityKey =
// new EntityKey ();
// ERROR The EntityKey property cannot be set to EntityNotValidKey, NoEntitySetKey, or a temporary key.
}
//To notify others listenging that the property has changed
this.OnPropertyChanged ("ContactInfoReference_ContactInfoID");
}
}
If I try to set the nullable field in the relationship to true then I get a compile error
'ContactInfoID' for type ContactInfo is not valid. All parts of the key must be non nullable.
I can load a User from the database which has a null ContactInfoID, but anytime I try to set the EntityKey to null I get exceptions.
How do I set the User.ContactInfoID to null?
User.ContactID cannot be set to -1 to represent a missing value; rather than mucking with the entitykey, can't you use null to do this? EF wasn't built to use -1 as that designation...
精彩评论