I'm trying to do an Upsert of an Advertisement object which contains a List<AdImage>. The Advertisement contains a foreign key that corresponds to a User. A user can have zero or more Advertisements, and an Advertisement has one or more AdImages.
The upsert fails with the following:
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.
Where the inner exeption is:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
The advertisement is instantiated very simply as:
var ad = new Advertisement
{
AdImages = new List<AdImage>
{
new AdImage {Image = model.Image}
},
Message = model.Message,
Title = model.Title,
User = user,
};
_aAdAppService.UpsertAdvertisement(ad);
The entities in question are defined as:
public class User : AbpUser<Tenant, User>
{ // AbpUser is a 3rd party class which defines Id as a primary key
public string AccessToken { get; set; }
public long UserId { get; set; }
public virtual List<Advertisement> Advertisements { get; set; }
}
public class Advertisement : Entity
{
[Key]
public long Id { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public List<AdImage> AdImages { get; set; }
public virtual User User { get; set; }
}
public class AdImage : Entity
{
[Key]
public int Id { get; set; }
public string Image { get; set; }
public virtual Advertisement Advertisement { get; set; }
}
This is how the relationships are defined:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Advertisements)
.WithRequired(x => x.User);
modelBuilder.Entity<Advertisement>()
.HasMany(a => a.AdImages)
.WithRequired(x => x.Advertisement);
modelBuilder.Entity<AdImage>()
.HasRequired(x => x.Advertisement);
base.OnModelCreating(modelBuilder);
}
What does the error message mean? I can't see how my relationships are defined incorrectly. How can I resolve this?