Controller
// 新增洗澡紀錄
[HttpPost("{babyid}")]
public ActionResult<Baby_Record_Entity> addBatheTime(int
babyid,[FromBody] BatheDto value)
{
var insert =
_Baby_Record_BatheService.creatBatheTime(babyid, value);
return CreatedAtAction(nameof(addBatheTime), new { id =
insert.Id }, insert);
}
Service
//新增洗澡時間
public Baby_Record_Entity creatBatheTime(int id,BatheDto
value)
{
Baby_Record_Entity insert = new Baby_Record_Entity
{
Baby = id,
time = value.time,
remark = value.remake
};
_MyDbContext.Add(insert);
_MyDbContext.SaveChanges();
return insert;
}
模型
namespace BabyRecords_Server.Entities
{
public class Baby_Record_Entity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
//嬰兒外鍵id
public virtual Baby_info_Entity Baby { get; set; }
public DateTime time { get; set; }
public string remark { get; set; }
public int recordClass { get; set; }
}
}
外鍵模型
namespace BabyRecords_Server.Entities
{
public class Baby_info_Entity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual User_Entity Users { get; set; }
public virtual Family_Group_Entity familGroup { get; set; }
public string babyName { get; set; }
public DateTime babyBirthday { get; set; }
public virtual ICollection<Baby_Record_Entity> babyrecord {
get; set; }
}
}
在Services的 Baby = id, 這邊會報錯
Cannot implicitly convert type 'int' to 'BabyRecords_Server.Entities.Baby_info_Entity'
請問是哪邊出了問題
小弟不才提供一下我的見解,看是否是這原因
//新增洗澡時間
public Baby_Record_Entity creatBatheTime(int id,BatheDto
value)
{
Baby_Record_Entity insert = new Baby_Record_Entity
{
Baby = id, //這樣應該會把id賦值給Baby所以報錯,應該要改成Id=id
time = value.time,
remark = value.remake
};
_MyDbContext.Add(insert);
_MyDbContext.SaveChanges();
return insert;
}
修改後程式碼,看看是否是你需要的
//新增洗澡時間
public Baby_Record_Entity creatBatheTime(int id,BatheDto
value)
{
Baby_Record_Entity insert = new Baby_Record_Entity
{
Baby = new Baby_info_Entity() {Id = id},
time = value.time,
remark = value.remake
};
_MyDbContext.Add(insert);
_MyDbContext.SaveChanges();
return insert;
}
Baby是外鍵 我要把id存到Baby
要把id存到Baby裡的Id嗎?
bsexp301479 對的
看看我後面修改的是否有幫助到你
還是不行...
報錯 Non-invocable member 'Baby_info_Entity' cannot be used like a method.
有把Baby_info_Entity的class引入嗎?
Model.Baby_Record_Entity insert = new Model.Baby_Record_Entity
{
Baby = new Model.Baby_info_Entity() {
Id = 1},
//time = "2021/10/22",
remark = "22222"
};
我自己用web api測試是可以寫進Baby裡的Id
bsexp301479 有了!!感謝!