gpt4 book ai didi

c# - Entity Framework 5 DbUpdateException : Null value for non-nullable member

转载 作者:太空狗 更新时间:2023-10-29 17:32:09 26 4
gpt4 key购买 nike

我有一些数据模型:

[DataContract(Name = "artist")]
public class artist : IEqualityComparer<artist>
{
[Key]
[XmlIgnore]
[DataMember]
public int ID { get; set; }

[DataMember]
[XmlElement(ElementName = "name")]
public string name { get; set; }

[DataMember]
[XmlElement(ElementName = "mbid", IsNullable = true)]
public string mbid { get; set; }

[DataMember]
[XmlElement(ElementName = "url")]
public string url { get; set; }

[XmlElement(ElementName = "image", IsNullable = true)]
public List<string> image { get; set; }

[DataMember(IsRequired=false)]
[XmlElement(ElementName = "stats", IsNullable = true)]
public stats stats { get; set; }

public double? match { get; set; }
public List<tag> tags { get; set; }
[XmlElement(ElementName = "similar")]
[DataMember(Name = "similar")]
public List<artist> similar { get; set; }

[DataMember]
[XmlElement(ElementName = "bio", IsNullable = true)]
public wiki bio { get; set; }


public bool Equals(artist x, artist y)
{
return x.name == y.name;
}

public int GetHashCode(artist obj)
{
return obj.name.GetHashCode();
}
}

和复杂类型:

    [DataContract]
[ComplexType]
[XmlRoot(ElementName = "streamable", IsNullable = true)]
public class stats
{
[DataMember(IsRequired = false)]
public int listeners { get; set; }

[DataMember(IsRequired = false)]
public int playcount { get; set; }
}

和数据库包含:

[Table("CachedArtistInfo")]
public class MusicArtists
{
[Key]
public string artistName { get; set; }
public artist artistInfo { get; set; }

private DateTime _added = default(DateTime);
[DataMember(IsRequired = true)]
[Timestamp]
public DateTime added
{
get
{
return (_added == default(DateTime)) ? DateTime.Now : _added;
}
set { _added = value; }
}
}

最后一步:

        foreach (artist a in id)
{
df.CachedArtists.Add(new MusicArtists() { artistName = a.name, artistInfo = a });
df.SaveChanges();
}

错误:异常类型 “System.Data.Entity.Infrastructure.DbUpdateException” “不可为 null 的成员的空值。成员:'stats'。”变量已完全填充,其中包含对象统计信息。怎么了?

enter image description here enter image description here

最佳答案

复杂类型不能为 null - 因此您必须在保存之前创建该类的实例。这篇文章帮助我解决了同样的问题。 http://weblogs.asp.net/manavi/archive/2011/03/28/associations-in-ef-4-1-code-first-part-2-complex-types.aspx

关于c# - Entity Framework 5 DbUpdateException : Null value for non-nullable member,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10279042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com