通过HTTP PUT将数据存储在数据库中



这是我的HTTP PUT方法。这段代码没有给出任何异常,但仍然没有将数据存储在数据库中。任何人都可以提供帮助。Model是我的getter setters类。

[HttpPut]
public HttpResponseMessage Addfood(int id,[FromBody] Model model)
{
Food food = new Food();
var userid = db.Users.FirstOrDefault(e => e.ID == id);
if (userid == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Record Found");
}
food.UID = id;
food.Name = model.Foodname;
food.Price = model.Foodprice;
food.Image = model.Foodimage;
food.Date_Time = DateTime.Today;
Category category = new Category();
category.Name = model.Categoryname;
db.Categories.Add(category);
food.CatID = category.ID;
db.Foods.Add(food);
db.SaveChangesAsync();
return Request.CreateResponse(HttpStatusCode.OK, food);
}

我的数据库表。

[dbo].[Food](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Image] [image] NULL,
[Price] [varchar](10) NULL,
[CatID] [int] NOT NULL,
[UID] [int] NOT NULL,
[Date/Time] [datetime] NULL,

[dbo].[Category](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[dbo].[User](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Phone] [numeric](18, 0) NOT NULL,
[Email] [varchar](50) NOT NULL,
[AID] [int] NOT NULL,
[Password] [varchar](50) NOT NULL,
[Date/time] [datetime] NULL,
[IsVerify] [bit] NULL,
[ProfilePicture] [image] NULL,

我从这个网址打电话

http://localhost:11434/api/Food/52

当我通过poston.点击这个请求时,这些是我在poster.中提供的参数。

{"Foodname":"Bir","Foodprice":"210","Categoryname":"H000"}

我在poster中得到了这个代码,但我的数据库没有更新。为什么此ID=0我的ID字段自动递增。

{
"ID": 0,
"Name": "Bir",
"Image": null,
"Price": "210",
"CatID": 0,
"UID": 52,
"Date_Time": "2018-12-05T00:00:00+05:00",
"Category": null,
"User": {
"ID": 52,
"Name": "h999",
"Phone": 3332158086,
"Email": "a.b.c@yahooooo.com",
"AID": 36,
"Password": "030021",
"Date_time": "2018-12-05T03:26:13.82",
"IsVerify": null,
"ProfilePicture": null,
"Address": null,
"Flags": [],
"Foods": [],
"Order_Tracking": [],
"Order_Tracking1": []
},
"FoodRecommendations": [],
"Order_Tracking": [],
"Ratings": []
}

尝试以下代码:

[HttpPut]
public HttpResponseMessage Addfood(int id,[FromBody] Model model)
{
Food food = new Food();
var userid = db.Users.FirstOrDefault(e => e.ID == id);
if (userid == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Record Found");
}
food.UID = id;
food.Name = model.Foodname;
food.Price = model.Foodprice;
food.Image = model.Foodimage;
food.Date_Time = DateTime.Today;
Category category = new Category();
category.Name = model.Categoryname;
food.Category = category;
db.Foods.Add(food);
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, food);
}

由于您还为新食物创建了一个新类别,因此需要使用food.Category=category而不是food.CatID,因为在调用SaveChanges方法之前,它不会被填充

相关内容

  • 没有找到相关文章

最新更新