In my project there are 2 classes (this will increase) Post and Product, both can have comments below is the structure i have created but its no working
I have created an interface for entities which can have comments
public interface ICommentable
{
int Id { get; set; }
}
Post and Product entities may have comments
public class Post : ICommentable
{
public int Id { get; set; }
public string Text { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Product : ICommentable
{
public int Id { get; set; }
public string Name { get; set; }
public int Rate { get; set; }
public ICollection<Comment> Comments { get; set; }
}
Comment Entity Itself
public class Comment
{
public int Id { get; set; }
public string Message { get; set; }
public int ItemId { get; set; }
public ICommentable Item{ get; set; }
}
Data Contxet
public class DataBaseContext:DbContext
{
public DbSet<Comment> Comments { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Product> Products { get; set; }
}
Entity framework doesn’t support interfaces so it is your first problem. The second problem is that navigation property cannot be normally “polymorphic” = you need separate navigation property (and FK) for every
ICommentableyou want to relate to yourComment:The only scenario where something similar can work is mapped inheritance but it would force your
PostandProductto inherit from mapped base entity and this inheritance will be reflected in the database. In such case you can have separate table for base entity and this table can have relation toComment(instead of derived tables).When working with relations always think about the way how would you done it in the database. Your classes mapped by EF must follow similar rules.