问题
In our database, we have the following tables
Tags
Id (int)
Name (string)
IsActive (bool)
TagType (string)
and
DocumentStyles
Id (int)
Name (string)
StyleRules (string)
IsAvailable (bool)
ThumbnailFileId (int nullable)
ConceptTagId (int nullable)
With the EF 4.2 designer, I've created the appropriate entities, and am trying to link the foreign key of ConceptTagId to the Tag model.
When I add the association (0..1 to many from Tag to DocumentStyle), it correctly links the foreign key and adds the navigation property of ConceptTag to the DocumentStyle object. I do not want a navigation property on the Tag object.
However, when calling the following code in a repository
db.DocumentStyles.Include(d => d.ConceptTag).ToList();
the resulting query attempts to access a property DocumentStyle_ID on the Tag table, which does not exist, nor should it. The foreign key is the ConceptTagId on the DocumentStyle table.
Where does this id column come from, and how can I get rid of it?
From the properties window of the relevant association:
End1 Multiplicity: * of DocumentStyle
End1 Nav Property: ConceptTag
End2 Multiplicity: Zero of One of Tag
End2 Nav Property: {NULL} (its blank in the property)
回答1:
Under further investigation, it comes with breaking the convention of naming styles. To resolve the issue, I had to implement in the OnModelCreating event the following rule
builder.Entity<DocumentStyle>().HasOptional(ds => ds.ConceptTag).WithMany();
This allows the framework to know that Tag has no reciprocal property to expect in the relationship and it doesnt attempt to find the DocumentStyle_Id property in future queries
来源:https://stackoverflow.com/questions/8476985/entity-framework-model-first-navigation-properties-adding-invalid-column-names-t