简体   繁体   中英

Entity Framework Model First Navigation Properties adding invalid column names to query?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM