I'm trying to configure EF to include documents when retriving a user or product. The entity Document has a ReferenceId property which should store either UserId or ProductId. This way, when I save a document for a user or product, the UserId or ProductId is saved to Document.ReferenceId.
Entities:
public class User { public string Id { get; set; } public ICollection<Document> Documents { get; set; } } public class Product { public string Id { get; set; } public ICollection<Document> Documents { get; set; } } public class Document { public string Id { get; set; } public string ReferenceId { get; set; } }
Configuring:
builder.Entity<User>(e => { e.HasKey(e => e.Id); e.Property(p => p.Id).ValueGeneratedOnAdd(); e.HasMany(e => e.Documents) .WithOne() .OnDelete(DeleteBehavior.Cascade); }); builder.Entity<Product>(e => { e.HasKey(e => e.Id); e.Property(p => p.Id).ValueGeneratedOnAdd(); e.HasMany(e => e.Documents) .WithOne() .OnDelete(DeleteBehavior.Cascade); }); builder.Entity<Document>(e => { e.HasKey(e => e.Id); e.Property(p => p.Id).ValueGeneratedOnAdd(); e.ToTable("Documents"); });
Saving:
var user = new User { }; var userDocument = new Document { ReferenceId = user.Id }; var product = new Product { }; var productDocument = new Document { ReferenceId = product.Id }; _context.Users.Add(user); _context.Products.Add(product); _context.Add(userDocument); _context.Add(productDocument); _context.SaveChanges();
Migrations:
migrationBuilder.CreateTable( name: "Documents", columns: table => new { Id = table.Column<string>(nullable: false), ReferenceId = table.Column<string>(nullable: true), ProductId = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Documents", x => x.Id); table.ForeignKey( name: "FK_Documents_Products_ProductId", column: x => x.ProductId, principalTable: "Products", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Documents_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); });
I don't want 2 foreign keys (ProductId and UserId) to be created on Documents table. Is there a way to make EF automatically link UserId and ProductId to ReferenceId?