Entity Framework 6 creates Id column even though other primary key is defined

c# data-annotations ef-fluent-api entity-framework entity-framework-6


I defined a DataObject as:

public class SensorType : EntityData
    public string CompanyId { get; set; }
    public string ServiceId { get; set; }

    public string Type { get; set; }

And used fluent API to make CompanyId and ServiceId a composite key:

            .HasKey(t => new { t.CompanyId, t.ServiceId });

//No autogeneration of PKs
modelBuilder.Entity<SensorType>().Property(t => t.ServiceId)
modelBuilder.Entity<SensorType>().Property(t => t.CompanyId)

Even though a Primary Key has been set Entity Framework creates a column named Id when I run Add-Migration:

            c => new
                    CompanyId = c.String(nullable: false, maxLength: 128),
                    ServiceId = c.String(nullable: false, maxLength: 128),
                    Type = c.String(),
                    Id = c.String(
                        annotations: new Dictionary<string, AnnotationValues>
                                new AnnotationValues(oldValue: null, newValue: "Id")

            .PrimaryKey(t => new { t.CompanyId, t.ServiceId })
            .Index(t => t.CreatedAt, clustered: true);


How do I prevent EF from adding this column?

9/19/2016 1:10:26 PM

Accepted Answer

I suspect it has something to do with the fact that you are deriving your class from EntityData and EntityData has a property named Id. My guess is that EF is getting confused because there is a property which adheres to it's key naming conventions (i.e. Id) and an explicitly defined key.

I suspect you'll have to tell it to explicitly ignore Id.

MSDN: EntityData Class


I'm assuming that you're working with Azure for this. This SO question has some additional information in the answers which may help you find an optimal solution.

However, I agree with @Basic in his comment to your question. I generally shy away from composite keys with EF due to the complexity (and other issues) they introduce. I suspect a unique constraint on your CompanyId and ServiceId fields will achieve what you want without involving them in the primary key for SensorType. That also means that you can just use the derived Id property as your primary key and avoid the entire issue all together. I don't know if it is feasible for your implementation, but it is something to consider.

5/23/2017 10:27:24 AM

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