目前我正在学习如何开发ASP.NET Web API使用的应用程序。我使用这些对象和Visual Studio生成的控制器(使用实体框架)创建了简单的Web API。
public class Client
{
public int ID { get; set; }
[Required]
public string Names { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Info { get; set; }
}
public class CustomTask
{
public int ID { get; set; }
[ForeignKey("Client")]
[Required]
public int ClientID { get; set; }
public virtual Client Client { get; set; }
[Required]
public string Technology { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Required]
public DateTime CreateDate { get; set; }
[Required]
public DateTime DueDate { get; set; }
[Required]
public long EstimatedTime { get; set; }
public long RealTime { get; set; }
[Required]
public decimal Price { get; set; }
[DefaultValue(false)]
[Required]
public bool Finished { get; set; }
[DefaultValue(false)]
[Required]
public bool Lessons { get; set; }
public string ArchiveID { get; set; }
}
在客户端(用WinForms编写)我试图以这样的方式将CustomTask
添加到现有Client
:
public static async Task PostObjectToAPI(object obj)
{
try
{
string typeName = obj.GetType().Name;
var response = await client.PostAsJsonAsync("/api/" + typeName + "s/", obj);
if (!response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
throw new APIexception(content);
}
}
catch (Exception ex)
{
throw ex;
}
}
private async void okButton_Click(object sender, EventArgs e)
{
CustomTask obj = new CustomTask();
obj.Client = clientSelected;
obj.ClientID = clientSelected.ID;
// getting rest of properties, I checked and it works good
await Connection.PostObjectToAPI(obj);
}
问题对我来说很奇怪:
我添加了例如ClientID = 2的新CustomTask 创建了新的CustomTask,但另外创建了新的Client,其除了ID之外的所有属性都相同。例如,此克隆的客户端ID = 5 最近创建的CustomTask的ClientID是5而不是2。
我做错了什么?在此先感谢您的帮助
修改
删除obj.Client = clientSelected;
行解决了问题。
答案 0 :(得分:2)
我怀疑你创建了EF没有跟踪的客户端对象,这就是为什么当你SaveChanges()
创建一个新对象时。所以,你有两个选择:
obj.Client = clientSelected;
- 这是导航属性,并在您保存更改后为您填充context.Attach(clientSelected)