具有一对多关系的 Azure GET 操作

Azure GET action with one-to-many relationship

我必须在 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
)

我使用 Entity Framework 数据库优先模型创建了 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 国家或 GET 城市 returns

500 Internal Server Error

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