I currently have a MVC5 site with a TPH relationship with classes as follows:
public abstract class product{
public int productID {get;set;}
}
public class toy : product {
public virtual List<ChildComment> Comments {get;set;}
public virtual List<AdultComment> Comments {get;set;}
}
public class tool : product {
public virtual List<AdultComment> Comments {get;set;}
}
public class ChildComment {
public CommentID {get;set;}
public string commentText {get;set;}
public virtual product Product {get;set;}
}
public class AdultComment {
public CommentID {get;set;}
public string commentText {get;set;}
public virtual product Product {get;set;}
}
My Issue is when: 1) I am creating a new adult comment in the adult comment controller 2) I use db.Products.find(id) to add a product to the product virtual property of the comment 3) I go to the view of the Product I just added the comment to and see that there are 0 comments (lets say I tried to add a comment to a toy, but remember I didn't cast it as a toy when I added it to the virtual property) 4) When I go to the database, there are 3 key columns in the adultcomment table: one for product, one for toys, and one for tools. The correct id was placed in the product column and the others are null
Do I have to cast a product as either a toy or tool before adding it to the adultcomment's virtual property?
Why are there extra columns in the adultcomment table, is it possible to consolidate to one single id column (since after all, i have one products table in my tph), and should I do so if it is possible?
Add the foreignKey attribute to new Comment class
public class Comment
{
[Key]
public int CommentID { get; set; }
public string commentText { get; set; }
public int productID { get; set; }
[ForeignKey("productID")]
public virtual Product Product { get; set; }
}
so AdultComment now looks like this
public class AdultComment : Comment
{
}
you will have to add a unique Identifier when creating a new product despite database auto generating id
using (var context = new YOUR-CONTEXT())
{
var toy = new Toy
{
productID = 1, //Unique identifier
AdultComments = new List<AdultComment>()
{
new AdultComment { commentText = "Some comment" }
}
};
context.Products.Add(toys);
context.SaveChanges();
}