[英]EF InvalidCastException With one to many relationship
将一对多关系实体添加到一个实体时,出现InvalidCaseException异常。 它在添加而不是在SaveChanges上失败。
无法将类型为“ System.Collections.Generic.List`1 [UserAccount]”的对象转换为类型为“ UserAccount”的对象。
试图将X的集合放在X的一个实例上
(父母或一个实体)
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false), Serializable()]
public class Merchant
{
/// <summary>
/// Standard ID
/// </summary>
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[DataType(DataType.Text), MaxLength(100)]
/// <summary>
/// UserFriendly Name
/// </summary>
public string MerchantName { get; set; }
/// Billing Information
/// </summary>
public virtual ICollection<BillingTransactions> BillingTransactions { get; set; }
/// <summary>
/// List of Accounts for this merchant (pulled from DBAccounts)
/// </summary>
public virtual ICollection<UserAccount> UserAccounts { get; set; }
}
(孩子还是很多)
public class UserAccount
{
private string loginID;
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
/// <summary>
/// Standard ID
/// </summary>
public int ID { get; set; }
public int MerchantId { get; set; }
[ForeignKey("ID")]
public Merchant Merchant { get; set; }
//Obviously there are more properties here....
}
我创建新实体,如下所示:
public void CreateNewMerchant(UserAccount useraccount)
{
Merchant merchant;
if (useraccount.Merchant == null) //New unknown merchant
{
merchant = new Model.Merchant.Merchant();
merchant.UserAccounts = new List<UserAccount>();
merchant.UserAccounts.Add(useraccount);
}
else
{
merchant = useraccount.Merchant;
}
ServiceBase<Merchant> sb = new Core.ServiceBase<Merchant>();
base.Add(merchant);
base.Save();
}
这是用于表单界面之类的向导的。 第一步是创建一个用户帐户。 下一步是填写新的商家信息。 向导步骤将创建子对象useraccount和一个空的父对象,然后在下一步中创建父对象。
我的代码是创建一个空白/空的父级,并将子级/用户帐户添加到空商家,然后添加到数据库。
为什么会收到无效的强制转换异常?
你需要...
[ForeignKey("MerchantId")]
public Merchant Merchant { get; set; }
...而不是[ForeignKey("ID")]
,它将使用主键作为外键并因此定义一对一而不是一对多的关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.