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

时间:2015-10-21 21:06:02

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

我必须在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 Database第一个模型创建了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 CITY返回

  

500内部服务器错误

1 个答案:

答案 0 :(得分:1)

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