【问题标题】:Web ApI Entity Framework (Code First) Value not appearing in databaseWeb ApI 实体框架(代码优先)值未出现在数据库中
【发布时间】:2015-05-14 13:01:51
【问题描述】:

我的数据库将正确运行,我可以通过 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);
    }

我通过 Postman 放了测试信息:

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

【问题讨论】:

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


    【解决方案1】:

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

    modelBuilder.Entity<Booking>()
                .HasRequired(b => b.Report) 
                .WithMany(b => b.Bookings) 
                .HasForeignKey(p => p.Report_Id);
    

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

    【讨论】:

    • 史蒂夫,非常感谢你的帮助,它解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多