Home > Net >  entities that do not expose foreign key properties for their relationships (EF)
entities that do not expose foreign key properties for their relationships (EF)

Time:09-03

When trying to call SaveChanges(), I get the following error:

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.'

SqlException: Invalid column name 'Artwork_Id'

I am using Entity Framework.

I'm trying to add an artworkImage that has the Id of an artwork as a reference. All information is being passed correctly but it's not saving.

public partial class ArtworkImage
{
    [Key]
    public int Id { get; set; }
    public string ImageURL { get; set; }
    public Artwork Artwork { get; set; }
}

public partial class Artwork
{
    [Key]
    public int Id { get; set; }
    public string Category { get; set; }
    public ICollection<ArtworkImage> ArtworkImage { get; set; }
}

My DbContext:

public DbContext()
        : base("name=DbConnection")
    {
        this.Configuration.AutoDetectChangesEnabled = false;
    }

    public virtual DbSet<Artwork> Artworks { get; set; }

    public virtual DbSet<ArtworkImage> ArtworkImages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Artwork>()
            .Property(e => e.Category)
            .IsFixedLength();

        Database.SetInitializer<DbContext>(null);
        base.OnModelCreating(modelBuilder);
    }

If any information is missing please point it out and I'll add it.

CodePudding user response:

You have to declare primary key on each table. it is a rare occasion when a table has no PK. almost never.

[Key]
public int Id { get; set; }

CodePudding user response:

So part of your problem might be that you don't define the relationship in reverse which I believe is important in how it establishes if the relationship is one-to-one or one-to-many. So you will likely need to add a property on the Artwork class that is of type ArtworkImage (if it is one-to-one). if it is one-to-many you will need to make the property some generic collection with the generic of type ArtworkImage.

One-to-one

public partial class Artwork
{
    [Key]
    public int Id { get; set; }
    public string Category { get; set; }
    public ArtworkImage ArtworkImage { get; set; }
}

One-to-many

public partial class Artwork
{
    [Key]
    public int Id { get; set; }
    public string Category { get; set; }
    public IEnumerable<ArtworkImage> ArtworkImages { get; set; }
}
  • Related