Juan José
Juan José

Reputation: 213

Identity column is not applied to the database

I have a class 'BudgetDetail' like this:

public class BudgetDetail
{
    public int Id { get; set; }
    public Budget Budget{ get; set; }
    public int BudgetId { get; set; }
    public Product Product { get; set; }
    public int ProductId { get; set; }
    public byte Quantity { get; set; }
    public int Price { get; set; }
    public int Iva { get; set; }
    public int Total { get; set; }
}

And this is the Fluent API configuration for this model:

public class BudgetDetailConfiguration: EntityTypeConfiguration<BudgetDetail>
{
    public BudgetDetailConfiguration()
    {
        ToTable("BudgetDetails");

        HasKey(pd => new { pd.Id, pd.BudgetId, pd.ProductId });

        Property(pd => pd.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

And when I made the migration, the identity of the Id property is setting to true but if I look in the database the identity it is set to false and I don't know why, I guess it is because I have composite keys to this table.

Identity column doesn't work if you have composite keys?

Upvotes: 1

Views: 43

Answers (1)

user3956566
user3956566

Reputation:

You have a BudgetId and a Budget - same for Product. Adding both does not mean they are related. The Budget object is unrelated to the BudgetId - the BudgetDetails class has two different attributes - one if BudgetId (FK) and one is an actual Budget object.

Remove your objects and keep their PKs - which are FKs within the BudgetDetail class.

public class BudgetDetail
{
    public int Id { get; set; }
    // public Budget Budget{ get; set; }
    public int BudgetId { get; set; }
    // public Product Product { get; set; }
    public int ProductId { get; set; }
    .../...
}

Upvotes: 1

Related Questions