Reputation: 706
Using Entity Framework Core 5, for M:N relationship, I created tables including the OrderProduct bridge table generated in SQL Server automatically. After that, I need to manage OrderProduct. How can I update the bridge table, OrderProduct using EF Core 5?
// Order
public class Order
{
public int Id { get; set; }
public DateTime dateTime { get; set; }
public DateTime? OrderFulfilled { get; set; }
public ICollection<Product> Products { get; set; }
}
// Product
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public ICollection<Order> Orders { get; set; }
}
// Need to manage ProductOrder with properties below
public class ProductOrder
{
public int Id { get; set; }
public int Quantity { get; set; }
public int ProductId { get; set; }
public int OrderId { get; set; }
public Order Order { get; set; }
public Product Product { get; set; }
}
Upvotes: 1
Views: 547
Reputation: 706
For someone who wants to use usingEntity for customizing the join table. I found this from here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity<PostTag>(
j => j
.HasOne(pt => pt.Tag)
.WithMany()
.HasForeignKey(pt => pt.TagId),
j => j
.HasOne(pt => pt.Post)
.WithMany()
.HasForeignKey(pt => pt.PostId),
j =>
{
j.Property(pt => pt.PublicationDate).HasDefaultValueSql("CURRENT_TIMESTAMP");
j.HasKey(t => new { t.PostId, t.TagId });
});
}
Upvotes: 1