我定期在我的ASP.NET页面上同步数据。我有一个具有两个复杂成员的对象,我在使用NotMapped属性的实体框架中忽略了它。相反,我存储序列化的值。
型号:
public class Game
{
//...
[NotMapped]
public Image Image { get; set; }
[NotMapped]
public List<Image> Images { get; set; }
public string Image_Serialized
{
get
{
return JsonConvert.SerializeObject(Image);
}
set
{
Image = JsonConvert.DeserializeObject<Image>(value);
}
}
public string Images_Serialized
{
get
{
return JsonConvert.SerializeObject(Images);
}
set
{
Images = JsonConvert.DeserializeObject<List<Image>>(value);
}
}
//...
}还有..。
public class Image
{
public string IconUrl { get; set; }
public string MediumUrl { get; set; }
public string ScreenUrl { get; set; }
public string SmallUrl { get; set; }
public string SuperUrl { get; set; }
public string ThumbUrl { get; set; }
public string TinyUrl { get; set; }
}同步完成后,我会更新我的数据库:
foreach(var game in games)
{
// address any null complex types.
if (game.Image == null) game.Image = new Image();
if (game.Images == null) game.Images = new List<Image>();
// add game if new, update if already in db
var dbGame = db.Games.Where(g => g.Id == game.Id).FirstOrDefault();
if (dbGame == null)
{
db.Games.Add(game);
}
else
{
var queriedGame = db.Entry(dbGame);
queriedGame.CurrentValues.SetValues(game);
queriedGame.State = System.Data.Entity.EntityState.Modified;
}
}
// returns 0 results... seems fine
var badGames = games.Where(g => g.Image == null || g.Images == null).ToList();
db.SaveChanges();我在db.SaveChanges()收到以下异常:
Server Error in '/' Application.
Null value for non-nullable member. Member: 'Image'.谢谢你的帮助。此外,如果我不希望它们的值直接存储在db (NotMapped属性)中,为什么我需要担心这些值为空?
发布于 2017-01-30 10:54:26
+1感谢阿里把我送到了正确的方向。
在将Image更改为struct并使Image引用可为still之后,我仍然有相同的错误。问题是Game对象引用了许多其他对象类型(开发人员、发行商、发行版等)。其中一些对象具有图像引用,而我尚未将其设置为NotMapped。我的假设是,当我调用db.SaveChanges()时,它试图将条目添加到这些数据表中,并导致问题。
发布于 2017-01-30 07:18:35
我不建议你使用这样的模型,而是在你的游戏类中使用图像id和图像的ICollection (事实上为什么两者都有)。
话虽如此,对于当前的模型,您可以尝试如下所示
public class Game
{
//...
[NotMapped]
public Image? Image { get; set; } //<== see ? to make it nullable
[NotMapped]
public List<Image> Images { get; set; }
public string Image_Serialized
{
get
{
if(Image == null)
return null;
return JsonConvert.SerializeObject(Image);
}
set
{
if(value == null)
Image = null;
else
Image = JsonConvert.DeserializeObject<Image>(value);
}
}
}发布于 2017-01-30 06:50:02
你可能需要使用Image?而不是使用Image作为数据类型。
https://stackoverflow.com/questions/41926829
复制相似问题