I'm using ASP.NET MVC to build an application for Forums. I have an entity named 'Posts' and an entity named 'PostReplies'.
On a particular Post, there will be a list of replies which are linked by a FK:'Post_Id' within my 'PostReplies' entity.
I'm wanting to know how I would go about deleting a Post which would then delete the replies linked to that post.
I've used Fluent API to try and solve this but I am getting this error message:
One or more validation errors were detected during model generation:
"BookClub.Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no >key defined. Define the key for this EntityType. BookClub.Data.IdentityUserRole: : EntityType 'IdentityUserRole' has no ?>key defined. Define the key for this EntityType. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based >on type 'IdentityUserLogin' that has no keys defined. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on >type 'IdentityUserRole' that has no keys defined."
I'm using MVC's default ApplicationDbContext and therefore have ApplicationUser's tables in my database.
Does anyone know how to rectify this issue?
POST ENTITY MODEL
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual Discussion Discussion { get; set; }
public virtual ICollection<PostReply> Replies { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
POSTREPLY ENTITY MODEL
public class PostReply
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual Post Post { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
DELETEPOST METHOD/LOGIC
public void DeletePost(Post post)
{
var deletePost = _context.Post.FirstOrDefault(p => p.Id == id);
if (deletePost != null)
{
_context.Post.Remove(deletePost);
_context.SaveChanges();
}
}
POSTCONTROLLER
[HttpGet]
public ActionResult DeletePost(int id)
{
return View(_postService.GetPost(id));
}
[HttpPost]
public ActionResult DeletePost(Post post)
{
var posts = new Post();
_postService.DeletePost(id, post);
return RedirectToAction("GetPostsByDiscussion","Discussion",
new { id = post.Id })
}
I have used Fluent API and written the following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PostReply>()
.HasRequired(p => p.Post)
.WithMany(p => p.Replies)
.HasForeignKey(r => r.PostId)
.WillCascadeOnDelete(false);
}