Web ApI实体框架(代码优先)价值未出现在数据库中

时间:2015-05-14 13:01:51

标签: sql-server entity-framework api rest ef-code-first

我的数据库将正常运行,我可以通过SQL Server手动输入数据,但是,当我尝试通过我的API传递值(使用Postman测试)时,该值不会传递到数据库中,它显示为“NULL”。

我有报告和预订表。

这是报告的代码:

public class Report
{

    public Report()
    {
        Injuries = new List<Injury>();
        this.Bookings = new HashSet<Booking>();
    }
    public int Id { get; set; }
    public string Club1 { get; set; }
    public string Club2 { get; set; }
    public virtual ICollection<Injury> Injuries { get; set; }
    public virtual ICollection<Booking> Bookings { get; set; }
    }

预订:

public class Booking
{
    //public Booking()
    //{
    //    Reports = new List<Report>();
    //}

    public int Id { get; set; }
    public string Club { get; set; }
    public string PlayerName { get; set; }
    public string PlayerNumber { get; set; }
    public string Reason { get; set; }
    public string Description { get; set; }

    //public int? Report_Id { get; set; }
    public Nullable<int> Report_Id { get; set; }

    public virtual Report Report { get; set; }

    //public virtual ICollection<Report> Reports { get; set; }
}

控制器:

     //POST: api/Reports
     [ResponseType(typeof(Report))]
     public async Task<IHttpActionResult> PostReport(Report report)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Reports.Add(report);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
    }

我通过邮递员提供测试信息:

I put the test information via Postman but the report_Id1 value won't pass into the database

Value appears as NULL

The information I enter manually via SQL Server, works fine.

I edit the Report_Id1 for Steven Gerrard and it appears when I call it via GET

我不确定为什么Report_Id会显示,因为它不是必需的,但Report_Id1是将报告和预订连接在一起的字段。

1 个答案:

答案 0 :(得分:0)

由于您的外键不遵循约定(ReportId),您需要使用注释[ForeignKey]或流畅的api配置:

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section

这就是EF添加第二个Report_ID1的原因。 https://msdn.microsoft.com/en-us/data/hh134698.aspx