My problem is that I'm trying to add a child entity, but keep running into problems.
Here's my situation:
I have a bunch of Profiles. Each Profile has a bunch of CategoryPriorities attached to it. Each CategoryPriorities has one AttributePriority attached to it.
When I update my model in Visual Studio I get the following:
I can without any trouble get the following to work:
CategoryPriority _categoryPriority = new CategoryPriority();
Profile _profile = DB.GetProfile(ProfileID);
_profile.CategoryPriorities.Add(_categoryPriority);
DB.savechanges()
But somehow the following will not work:
AttributePriority _attributePriority = new AttributePriority();
CategoryPriority _categoryPriority = new CategoryPriority();
_categoryPriority.AttributePriorities.Add(_attributePriority);
// Error! There is no option of "Add" or any other operation for the matter.
Profile _profile = DB.GetProfile(ProfileID);
_profile.CategoryPriorities.Add(_categoryPriority);
DB.savechanges()
I'm guessing this is due to how the EF model is set up. Ideally I would like to have an one-to-one between CategoryPriority and AttributePriority tables.
I'll add an image of my model.
Any ideas? Any help much appreciated!
Edit: I've added images to my post.
Funny thing is that if I write:
Profile _p = new Profile();
There is no option of _p.Add
there either.. obviously I'm missing something..
Edit 2: Ok, so I got it to work, almost... I know, not the most aesthetically pleasing code, I'm working on that..
Profile _profile = this.GetProfile(this.GetUserID(arrangeattributesviewmodel.ProfileID));
int iter = 0;
foreach (AttributeListForCategory _category in arrangeattributesviewmodel.AllAttributesForCheckBoxList.CategoryAttributeList)
{
iter++;
CategoryPriority _categoryPriority = new CategoryPriority();
_categoryPriority.ProfileID = arrangeattributesviewmodel.ProfileID;
_categoryPriority.CategoryID = _category.CategoryID;
_categoryPriority.CategoryName = _category.CategoryName;
_categoryPriority.CategoryID = _category.CategoryID;
_categoryPriority.CategoryPriorityNR = iter;
AttributePriority _attributePriority = new AttributePriority();
_attributePriority.AttributePriorityString = _category.CompilePriorityString();
_categoryPriority.AttributePriority = _attributePriority;
_profile.Catego开发者_运维百科ryPriorities.Add(_categoryPriority);
db.SaveChanges(); // It fails here with the message below..
}
{"A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'CategoryPriorityID'."}
Any ideas?
Edit 3: Solved it!
I had to instanciate an AttributePriority in my CategoryPriority...
Your relation between CategoryPriority
and AttributePriority
is 1:0..1 so there is not Add
method. You simply call:
_categoryPriority.AttributePriority = attributePriority;
Btw. how is it possible that your entity define AttributePriority
but your code uses AttributePriorities
? It should not compile.
Make sure you have foreign keys set up correctly and then regenerate your model.
精彩评论