这是对象Image
public int Id { get; } //primary key
public string Path { get; set; } //not null
public string Name { get; set; } //not null
public string Url { get; set; } //allows null
public string SecureUrl { get; set; } //allows null
EFDbImageRepository
public void UploadToCloud(Image image)
{
System.Diagnostics.Debug.WriteLine(image.Id);
if(image.Id == 0)
{
context.Images.Add(image);
}else
{
Image dbEntry = context.Images.Find(image.Id);
}
context.SaveChanges();
}
在UploadImage操作中的控制器
...
Image image = new Image();
image.init(path, "defaultName1", "type");
imageRepository.UploadToCloud(image);
...
目前UploadToCloud我有例外:
'System.Data.Entity.ModelConfiguration.ModelValidationException' in EntityFramework.dll
似乎数据有问题,我试图保存,但我不明白错误。此时我只初始化了两个字段Path和Name。我应该自动设置ID,Url和SecureUrl允许为null,所以一切都应该是好的。
如何将对象保存到数据库?
答案 0 :(得分:1)
您只读了Id
字段。实体frameworke忽略只读属性,因此您现在已经创建了一个实体而没有主键。您至少要添加private set
,但为什么不添加普通(公开){get;set;}
?。