EntityFrameworkCore: How to save an entity with ForeignKey to another model?

asp.net-core asp.net-core-mvc asp.net-core-webapi c# entity-framework-core


I have a model that relates to another:

public class Portfolio : BaseEntity, IEntityBase
        public string Name { get; set; }
        public Org Organization { get; set; }
        public bool IsPrivate { get; set; }

When I try to save it (pointing the value of the organization field to an existing record in the database), the ModelState is not valid ("Organization": The input was not valid).

I send the id of the Organization with the rest of the payload:

    "Name": "Port 1",
    "Organization": 16

and the Controller code is very simple:

public IActionResult Create([FromBody]Portfolio item){
     if (ModelState.IsValid){
         return new OkObjectResult(item);
        return BadRequest(ModelState);

The interesting part is that when I specify the Organization field in the payload, the item in the Create() method will come as null so I can't manually retrieve the Organization from its repo and link to Portfolio either. When I omit the Organization, it will save the entity just fine.

If I enclose the details of the Organization inside the payload, then the EF will save a new Organization record in the database. But how do I link to existing one vs saving a new model?

6/10/2017 5:51:13 AM

Accepted Answer

In your Portfolio model you have this property:

public Org Organization { get; set; }

Please note the type of the property is Org. So setting it to a number will not work for obvious reasons. Try changing your model a little to something like this:

public int OrganizationId { get; set; }

public Org Organization { get; set; }

That will tell EF that the Organization property is a navigation property and the foreign key for it is OrganizationId. Set the OrganizationId property and it should work.

6/10/2017 5:55:57 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow