Creating an Entity creates a "No parameterless constructor defined for this object"

I am working on a basic MVC5 / EF6 application and am in the following error:

No parameterless constructor defined for this object. 

This happens when I use the standard actions and default views that Visual Studio 2013 creates when creating a new controller. I did not edit anything in these generated files ( TestItemController , Views/TestItem/Create.cshtml ). My objects on which the controller is located are as follows:

 public class TestItem { private Category _category; // Primary key public int TestItemId { get; set; } public int CategoryId { get; set; } public string TestColumn { get; set; } public virtual Category Category { get { return _category; } set { _category = value; } } protected TestItem() { } public TestItem(Category category) { _category = category; } } public class Category { private ICollection<TestItem> _testItems; // Primary key public int CategoryId { get; set; } public string Description { get; set; } public virtual ICollection<TestItem> TestItems { get { return _faqs; } set { _faqs = value; } } public Category() { _testItems = new List<TestItem>(); } } 

I assume this is due to the TestItem class, which has a constructor that accepts a Category object that must support an anonymous domain model. TestItem cannot be created without a category. But, as far as I know, the protected parameterless constructor should be used by EF in this exact case with lazy loading, etc.

What is going on here, or what am I doing wrong?

UPDATE: The controller looks like this (trimmed):

 public class TestItemsController : Controller { public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "TestItemId,OtherColumns")] TestItem testItem) { if (ModelState.IsValid) { db.TestItems.Add(testItem); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(testItem); } } 
+5
source share
1 answer

Of course, EF can use protected constructors, but scaffolding creates action methods to create a new element. These action methods require a parameterless constructor.

You can find some details of these creation methods here .

+3
source

Source: https://habr.com/ru/post/1200530/


All Articles