I need to add 'notes' to multiple entities in my EF Core 6 data model. Notes have exactly the same schema - a date/time, the name of the person who created the note, and a comment - so I'd like to use a single database table, with a discriminator column on each Note
record which indicates which relationship/entity it belongs to.
My entity model looks like this:
public class Note {
public int Id { get; set; }
public DateTime CreatedAt { get; set;}
pulic string CreatedBy { get; set; }
public string Comments { get; set; }
}
public class Customer {
public int Id { get; set; }
public string Name { get; set; }
public List<Note> Notes { get; set; }
}
public class Supplier {
public int Id { get; set; }
public string Name { get; set; }
public List<Note> Notes { get; set; }
}
and I'm trying to map the appropriate properties on my DbContext
to produce this set of tables:
Notes
+----+------------+----------+------------------+------------+----------------------------------+
| Id | EntityType | EntityId | CreatedAt | CreatedBy | Comments |
+----+------------+----------+------------------+------------+----------------------------------+
| 1 | Customer | 17 | 2022-01-22T18:22 | alice | Cancelled erroneous invoice |
| 2 | Supplier | 19 | 2022-01-23T12:52 | bob | Amended booking date to April |
| 3 | Customer | 24 | 2022-01-24T19:07 | bob | Refunded duplicated order |
| 4 | Customer | 17 | 2022-01-27T18:22 | alice | Added Bryan Smith as contact |
| 5 | Supplier | 22 | 2022-01-27T20:17 | carol | Override booking terms for 2022 |
+----+------------+----------+------------------+------------+----------------------------------+
Customers
+----+------------------+
| Id | Name |
+----+------------------+
| 17 | Fisher Price Plc |
| 24 | Bob's Bikes Ltd |
+----+------------------+
Suppliers
+----+-------------------------+
| Id | Name |
+----+-------------------------+
| 19 | Wigs'r'Us International |
| 22 | Monkeys Unlimited |
+----+-------------------------+
Anybody know what combination of properties, entities and discriminators I can use to get this working?
I've tried creating a SupplierNote
and CustomerNote
class, which inherit from Note
, and then mapping them like this:
modelBuilder.Entity<Note>()
.HasDiscriminator<string>(note => note.EntityType)
.HasValue<CustomerNote>(nameof(Customer))
.HasValue<SupplierNote>(nameof(Supplier));
but this creates a Note
table with CustomerId
and SupplierId
columns, which isn't what I'm after.