Search code examples
postasp.net-web-apientity-framework-6asp.net-web-api2asp.net-web-api-routing

Post request to database associated with primary and foreign key in web api using Entity Framework


I have a database with three tables with primary and foreign key association .

I am using Web API and Entity Framework to auto generate methods. I have been successful doing that. But I want to insert into a table with foreign key separately.

Currently, I am able to get a JSON object for the main table which has primary key and navigation properties to the table with a foreign key. enter image description here

I have created the web api using auto generate read write action methods like . enter image description here

I am able to access the json object for floors database and accordingly for Meter and Router . So , I have a post method "/api/floorinfoes" with POST . But , what to do , if i want to insert separately into RouterInfo table and MeterInfo table .Eg: If i want to insert one row in MeterInfoes table, then how to proceed with that .


Solution

  • If you want to insert one row in MeterInfoes Table.

    public class MeterInfo
    {
            [Key]
            public int MeterId { get; set; }
            public string MeterName { get; set; }
    
            public int? FloorId { get; set; }
    
            [ForeignKey("FloorId")]
            public FloorInfo FloorInfo { get; set; }
    }
    

    Add your entities to DbContext, if not done already

    public class DbContext : IdentityDbContext<IdentityUser>
    {
    
            public DbSet<FloorInfo> FloorInfos { get; set; }
            public DbSet<MeterInfo> MeterInfos { get; set; }
            public DbSet<RouterInfo> RouterInfos { get; set; }
    }
    

    Create a new controller MeterInfoController or auto generate using scaffolding

    public class MeterInfoController : ApiController
    {
    
        public IHttpActionResult Post(MeterInfo meterInfo)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    
             db.MeterInfo.Add(meterInfo);
             db.SaveChanges();
    
            return Ok(meterInfo);
        }
    }
    

    To consume this endpoint, for example:

    Url : /api/MeterInfo
    

    If you know the FloorId

       Post Data : {"MeterId": 1, "MeterName" : "Test" , "FloorId" : 10 } 
    

    If you do not know the FloorId, but make sure FloorId in MeterInfo is nullable

     Post Data:  {"MeterId": 1, "MeterName" : "Test"} 
    

    I think the answer is to auto generate API Controllers for both MeterInfo and RouterInfo.