destructi6n destructi6n - 3 months ago 15
C# Question

Error adding entities to database

I'm getting the following exception message:


An error occurred while saving entities that do not expose foreign key
properties for their relationships. The EntityEntries property will
return null because a single entity cannot be identified as the source
of the exception. Handling of exceptions while saving can be made
easier by exposing foreign key properties in your entity types. See
the InnerException for details.


And my inner exception is related to me change column names on my table as they didn't make sense before (They were given the name Customer_Customer_ID) and renamed my Sku and my Customer objects that are composed in my cart, with the following data annotations

[Table("Cart")]
public class Cart
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }


public Guid CartID { get; set; }

[Column("SkuID")]
public virtual Sku Sku { get; set; }

[Required]
public int Quantity { get; set; }

[Column("CustomerID")]
public virtual Customer Customer { get; set; }

public bool IsCheckedOut { get; set; }



}


This is the inner exception of the exception message


"Invalid column name 'Customer_Customer_ID'.\r\nInvalid column name
'Sku_SKU_ID'."


What is the correct way to name these composed objects and do I need to modify my OnModelCreating to reflect these changes to entity framework?

Answer

Add a SkuID and CustomerId property to your entity class.

public class Cart
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public Guid CartID { get; set; }

    public int SkuID { set;get;}

    public virtual Sku Sku { get; set; }

    [Required]
    public int Quantity { get; set; }

    public int CustomerID{ set;get;}

    public virtual Customer Customer { get; set; }

    public bool IsCheckedOut { get; set; }
}

Assuming your Sku and Customer class has an ID property of type int and it is the primary key. EF will create Cart table with foreign keys to Sku and Customer table(s) properly because the current structure follow the convention.

Now your entity class has both integer Id (CustomerID) and the navigation property (Customer)