我有一个Client和一个Assignmnet类。关系是客户可以有多个任务。
public class Assignment
{
public DateTime created { get; set; }
public DateTime? updated { get; set; }
[ForeignKey("clientId")]
public virtual Client client { get; set; }
[ForeignKey("client")]
public int clientId { get; set; }
[Key]
public int id { get; set; }
}
public class Client
{
public DateTime created { get; set; }
public DateTime? updated { get; set; }
public virtual IEnumerable<Assignment> assignments { get; set; }
[Key]
public int id { get; set; }
}
以下代码有效。客户端和clientId都设置为正确的值。
var clientController = GetClientController();
Client c = new Client();
clientController.PostClient(c);
var assController = GetAssignmentController();
Assignment a = new Assignment();
a.client = c;
assController.PostAssignment(a);
但以下代码不起作用。 clientId已更新,但客户端为空。
var clientController = GetClientController();
Client c = new Client();
clientController.PostClient(c);
var assController = GetAssignmentController();
Assignment a = new Assignment();
a.clientId = c.id;
assController.PostAssignment(a);
分配控制器的工作原理如下:
public HttpResponseMessage PostAssignment(Assignment assignment)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
try
{
_db.Insert(assignment);
_db.Save();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, assignment);
return response;
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
有人知道我做错了吗?