【问题标题】:Azure GET action with one-to-many relationship具有一对多关系的 Azure GET 操作
【发布时间】:2015-10-21 21:06:02
【问题描述】:

我必须在 Azure SQL 数据库中创建具有一对多关系的表。

--Countries
create table Countries
(
    ID int not null primary key clustered identity,
    Name varchar(100) not null
)
--Cities
create table Cities
(
    ID int not null primary key clustered identity,
    Name varchar(100) not null,
    CountryID int not null foreign key references Countries(ID) on delete cascade
)

我使用实体框架数据库第一个模型创建了 Web API。生成的类如下所示:

Country.cs

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Country()
    {
        this.Cities = new HashSet<City>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<City> Cities { get; set; }

City.cs

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public City()
    {

    }

    public int ID { get; set; }
    public string Name { get; set; }
    public int CountryID { get; set; }    
    public virtual Country Country { get; set; }

CitiesController.cs

    private TripperDBEntities db = new TripperDBEntities();

    // GET: api/Cities
    public IQueryable<City> GetCities()
    {
        return db.Cities;
        }

// POST: api/Countries
        [ResponseType(typeof(Country))]
        public async Task<IHttpActionResult> PostCountry(Country country)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Countries.Add(country);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = country.ID }, country);
        }

调用 GET Country 或 GET Cities 返回

500 内部服务器错误

【问题讨论】:

  • HTTP 响应代码 500(通常)表示处理请求时发生异常。您需要检查服务器端日志并找出异常是什么。从那里可能会清楚问题是什么。
  • 查看 get 操作的代码也很方便。
  • 我在我的问题中添加了 get 和 put 操作。我认为我的代码需要更新以跟踪服务器端日志。
  • 仍然有点困惑 - 当您说“当我将第一个城市添加到数据库时,GET 操作返回 500 错误”时,第一个城市是如何添加的,您是否真的遇到了 GET 问题还是 PUT 操作?
  • 对不起,应该有 POST 动作。添加和获取国家/地区没有任何问题。另外,如果我没有任何城市,则 api 响应正确。添加第一个城市后,我无法获得城市或国家/地区。

标签: c# entity-framework rest azure-sql-database asp.net-web-api


【解决方案1】:

如果您加载相关数据,它会创建一个圆形对象图。 有关如何处理的更多信息,请查看以下内容:http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多