Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity creation throws "No parameterless constructor defined for this object"

I'm working on a basic MVC5/EF6 application and am running into the following error:

No parameterless constructor defined for this object.

This happens when I use the default Create Action and View that are scaffolded by Visual Studio 2013 when you create a new Controller. I have not adjusted anything within those generated files (TestItemController, Views/TestItem/Create.cshtml). My entities on which the controller is scaffolded look like this:

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'm guessing this is due to the TestItem class having the constructor taking in a Category object, which is there to keep the domain model anemic. A 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 when lazy loading etc.

What's 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);
    }
}
like image 606
Steven Thewissen Avatar asked Oct 20 '22 03:10

Steven Thewissen


1 Answers

Sure, EF can use protected constructors, but scaffolding creates action methods for creating a new item. These action methods require a parameterless public constructor.

You can find some details of these create methods here.

like image 113
Gert Arnold Avatar answered Oct 27 '22 11:10

Gert Arnold