简体   繁体   中英

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

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:

[HttpPost]
public IActionResult Create([FromBody]Portfolio item){
     if (ModelState.IsValid){
         _PortfolioRepo.Add(item);
         _PortfolioRepo.Commit();
         return new OkObjectResult(item);
         }
     else{
        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?

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; }

[ForeignKey("OrganizationId")]
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM