I have simple one-to-many relations.
public partial class LinkedDocument
{
public Guid Id { get; set; }
public Guid DocumentId { get; set; }
public virtual TblDocumentData Document { get; set; }
}
public partial class TblDocumentData : IEntity<Guid>
{
public Guid Id { get; set; }
// other props
public virtual ICollection<LinkedDocument> LinkedDocuments { get; set; } = new HashSet<LinkedDocument>();
}
modelBuilder.Entity<LinkedDocument>(
entity =>
{
entity.ToTable("LinkedDocument");
entity.HasKey(e => new {e.Id, e.DocumentId})
.HasName("PK_LinkedDocument")
.IsClustered(false);
entity.Property(e => e.Id).ValueGeneratedNever();
entity.HasOne(d => d.Document)
.WithMany()
.HasForeignKey(d => d.DocumentId)
.HasConstraintName("FK_LinkedDocument_TBL_DocumentData_DocumentId")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
});
and for TBL_DocumentData fluent api (only part)
entity.HasMany(d => d.LinkedDocuments)
.WithOne(d => d.Document)
.HasForeignKey(d => d.DocumentId)
.IsRequired();
On Save I have code like this:
this._ctx.Set<TblDocumentData>().Add(documentData);
this._ctx.Set<LinkedDocument>().Add(new LinkedDocument {Id = attachmentModel.EntityId, DocumentId = documentData.Id});
await this._ctx.SaveAsync(cancellationToken);
but on save I see error: Invalid column name 'TblDocumentDataId'. From debug console I can see that SQL script is generated like this:
INSERT INTO [LinkedDocument] ([DocumentId], [Id], [TblDocumentDataId])
VALUES (@p22, @p23, @p24);
Searching by solution - cannot find column TblDocumentDataId
- so this is something added by EF.
What I missed in configuration of my one-to-many relation?
Try changing entity.HasOne(d => d.Document).WithMany()
to:
entity
.HasOne(d => d.Document)
.WithMany(data => data.LinkedDocuments)
And you can remove the setup from entity.HasMany(d => d.LinkedDocuments)
(I would argue that there is no point to setup the same twice).