Reputation: 3553
I have a table Items
and table Services
.
Each item needs to have relation to one service.
How can I write relation between those 2 via ItemServices
relational table in EF Fluent api?
Here are classes
public class Item
{
public Guid Id { get; private set; }
public Service Service { get; private set; }
}
public class ItemService
{
public int ServiceId { get; set; }
[ForeignKey(nameof(ServiceId))]
public Service Service { get; set; }
public int ItemId { get; set; }
[ForeignKey(nameof(ItemId))]
public Item Item { get; set; }
}
public class Service
{
public int Id { get; private set; }
public string ServiceCode { get; set; }
}
Please note that i do not want to have relation table inside my Item object, so I do not want to use it like item.ItemService.Service
, but as a item.Service
Upvotes: 1
Views: 316
Reputation: 7360
On which version of Entity Framework you are working ?
If you ask about EF Core then you can find very good help here:
BTW: I have similar case in my project and it's working by convention.
Of course I have configured DbSet<>
in my ApplicationDbContext
(I'm not sure how it's work in earlier versions of EF):
Is there something other reason for using ItemService object or it's for relationship purpose only ?
If you use ItemService
only for relationship purpose then you don't need it in your case - try something like that:
public class Item
{
public Guid Id { get; set; }
public Service Service { get; set; }
}
public class Service
{
public int Id { get; set; }
public string ServiceCode { get; set; }
public Item Item { get; set; } //for One to One relationship
// or
public virtual ICollection<Item> Items { get; set; } // for One service to Many Items relationship
}
and in ApplicaitionDbContext
:
public virtual DbSet<Item> Items { get; set; }
public virtual DbSet<Service> Services { get; set; }
Upvotes: 1