EF auto generates foreign key field while making database transaction which is not exist

c# entity-framework entity-framework-6


I'm working on one project where we use entity framework for database transaction. While making a database transaction, if there's any reference key in particular table, then it autogenerates new field for that referenced entity which doesn't even exist.

For Example:

I've one table called Stations which has a reference of StationTypes(one-to-one).

Now whenever we try to create/update any record in Stations table, it by defaylt inject one field called "StationType_Id" into particular query called "StationType_Id" - which is not even exist and end up in throwing bellow error.

Invalid column name 'StationTypes_Id'.

Sample DB entity generated by EF

public partial class Stations
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Stations()
        this.OrganizationStations = new HashSet<OrganizationStations>();

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int StationTypeId { get; set; }
    public int Status { get; set; }
    public int CreatedBy { get; set; }
    public System.DateTime CreatedDate { get; set; }
    public Nullable<int> UpdatedBy { get; set; }
    public Nullable<System.DateTime> UpdatedDate { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OrganizationStations> OrganizationStations { get; set; }
    public virtual StationTypes StationTypes { get; set; }
6/25/2019 3:06:44 PM

Popular Answer

This looks like it would actually be a Many-to-1 relationship. A Station has 1 station type, but many stations may have that same station type.

In this case, it would be expected that a Station record would have a StationTypeId column. You will likely not want to expose a StationTypeId property in your Station entity so to map this in EF 6:

using modelBuilder

   .HasRequired(x => x.StationType)
   .Map(x => x.MapKey("StationTypeId"));

A 1-to-1 relationship would have the StationType table sharing a StationId PK with the Station table. In this case a Station would have a reference to a StationType, and a StationType would have a reference to a Station. EF would then link these together by PK:

   .HasRequired(x => x.StationType)
   .WithRequired(x => x.Station);

This can be set up with a FK to FK relationship, but one FK must be null-able.

6/23/2019 10:24:58 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow