How To overcome this error in mvc insert statement

Posted by Srujana under ASP.NET on 4/26/2012 | Points: 10 | Views : 993 | Status : [Member] | Replies : 0
Hi,

I wrote the following code for inserting data into database using EDM

but I got the EROR as

The INSERT statement conflicted with the FOREIGN KEY constraint \"Comments_Blog\". The conflict occurred in database............

Below is my code

public class BlogDbContext:DbContext
{
public DbSet<Blog> Blog { get; set; }
public DbSet<Comments> Comments { get; set; }
}

public class Comments
{
[Key]
public int CommentId { get; set; }
public string Comment { get; set; }
//[ForeignKey]
public int BlogId { get; set; }

[Required(ErrorMessage = "BlogName is required")]
public string BlogName { get; set; }//If I didnt add this I cant get get this in view only BlogId and Comment only cmae
public virtual Blog Blog { get; set; }
}

public class Blog
{
[Key]
public int BlogId { get; set; }

[Required(ErrorMessage = "BlogName is required")]
public string BlogName { get; set; }

[Required(ErrorMessage = "Description is required")]
[StringLength(120, ErrorMessage = "Description Name Not exceed more than 120 words")]
public string Description { get; set; }
public string Body { get; set; }
public virtual List<Comments> Comments_List { get; set; }

}

this is my controller

public class Default1Controller : Controller
{
BlogDbContext _db = new BlogDbContext();


//
// GET: /Default1/

public ActionResult Index()
{
var GenreLst = new List<string>();

var GenreQry = from d in _db.Blog
orderby d.BlogName
select d.BlogName;
GenreLst.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreLst);

return View(_db.Comments.ToList());

}

//
// GET: /Default1/Details/5

public ActionResult Details(int id)
{
return View();
}

//
// GET: /Default1/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Default1/Create

[HttpPost]
public ActionResult Create(Comments Comments)
{
if (ModelState.IsValid)
{
_db.Comments.Add(Comments);
_db.SaveChanges();
return RedirectToAction("Index");
}

return View(Comments);
}

If anybody knows the Answer Plz help me




Responses

(No response found.)

Login to post response