简体   繁体   English

将对象添加到 DBSet 时出现 InvalidCastException

[英]InvalidCastException when Adding Object to DBSet

I have two classes我有两节课

[Table("Kunden")]
public class Kunde
{

    public Guid Id { get; set; }
 

    [Required, ForeignKey("Id")]
    public virtual List<Standort> OrtStandort { get; set; }

    
    public Kunde()
    {
        Id = Guid.NewGuid();
        OrtStandort = new List<Standort>();
    }
}

[Table("Standorte")]
public class Standort
{
    public Guid Id { get; set; }

    public Standort()
    {
        Id = Guid.NewGuid();
        //KontaktAnsprechpartner = new List<Ansprechpartner>();
    }
}

public class HausarbeitContext : DbContext
{
    public DbSet<Kunde> Kunden { get; set; }
    
    public DbSet<Standort> Standort { get; set; }
    
    // ...
}
         
         
         

As soon, as the debugger hits:一旦调试器命中:

 haDB/*HausarbeitContext*/.Kunden/*DbSet<Kunde>*/.Add(kunde);

I get:我得到:

System.InvalidCastException: 'Das Objekt des Typs "System.Collections.Generic.List`1[ClassDesigner.Part_Hausarbeit.Data.Standort]" kann nicht in Typ "ClassDesigner.Part_Hausarbeit.Data.Standort" umgewandelt werden.' System.InvalidCastException: 'Das Objekt des Typs "System.Collections.Generic.List`1[ClassDesigner.Part_Hausarbeit.Data.Standort]" kann nicht in Typ "ClassDesigner.Part_Hausarbeit.Data.Standort" umgewandelt werden.' (can not be converted) (无法转换)

See the Objekt: enter image description here查看对象:在此处输入图像描述

You might need to include the full definitions for the 2 entities.您可能需要包含 2 个实体的完整定义。 At a glance, one thing that stands out is this: // Knude一目了然,突出的一件事是:// Knude

[Required, ForeignKey("Id")]
public virtual List<Standort> OrtStandort { get; set; }

The ForeignKey attribute is typically applied on the "One" side of a Many-to-One. ForeignKey 属性通常应用于多对一的“一”侧。 Additionally, while I don't believe it is a requirement, collection references are typically declared as ICollection<T> rather than List<T> .此外,虽然我认为这不是ICollection<T> ,但集合引用通常声明为ICollection<T>而不是List<T> EF will be looking to establish proxies for virtual members so it's advisable to leave these references as a lower level interface type. EF 将寻求为virtual成员建立代理,因此建议将这些引用保留为较低级别的接口类型。

Given a Kunde & Standort parent-children relationship, the FK references would more normally be:鉴于 Kunde 和 Standort 的亲子关系,FK 引用通常是:

public class Kunde
{
     [Key]
     public Guid Id { get; set; }

     public virtual ICollection<Standort> OrtStandort { get; set; } = new List<Standort>();
}

public class Standort
{
    [Key]
    public Guid Id { get; set; }
    
    public Guid KundeId { get; set; }
    [ForeignKey("KundeId")]
    public virtual Kunde Kunde { get; set; }
}

The FK for the Kunde-Standort relationship is managed in the Many side for the singular ID column pointing back to the parent. Kunde-Standort 关系的 FK 在多侧管理,用于指向回父的单数 ID 列。

Or, to exclude the KundeId property inside of Standort entity, leveraging a shadow property (EF Core) or mapping it without defining a field using Map(x => x.MapKey("KundeId")) in EF 6.或者,要排除 Standort 实体内的KundeId属性,请利用影子属性 (EF Core) 或在不使用 EF 6 中的Map(x => x.MapKey("KundeId"))定义字段的情况下对其进行Map(x => x.MapKey("KundeId"))

On a side note, when using Guids for Key columns, I would strongly recommend leveraging a Database generated approach (Marking the columns as Identity ) rather than set in code, and then setting these up to use sequential GUID generation.附带说明一下,当对 Key 列使用 Guid 时,我强烈建议利用数据库生成的方法(将列标记为Identity )而不是在代码中设置,然后将它们设置为使用顺序 GUID 生成。 For example, with SQL Server, using NEWSEQUENTIALID() instead of NEWID() :例如,对于 SQL Server,使用NEWSEQUENTIALID()而不是NEWID()

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

If you do need to set them in code then I would look at options to generate a GUID in an index-friendly manner for your selected database and implement a Guid generator that can arrange the various elements that make up a GUID so that the database indexing can sort through them efficiently.如果您确实需要在代码中设置它们,那么我将查看以索引友好的方式为您选择的数据库生成 GUID 的选项,并实现一个 Guid 生成器,该生成器可以排列构成 GUID 的各种元素,以便数据库索引可以有效地对它们进行分类。 The default randomized .Net GUID will lead to considerable Index table fragmentation.默认的随机 .Net GUID 会导致大量的索引表碎片。 In systems that could see more than 10's of thousands of rows this can lead to considerable memory/disk usage issues and performance issues.在可以看到超过 10 行的系统中,这可能会导致相当大的内存/磁盘使用问题和性能问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 共享数据并添加到ObservableCollection时出现InvalidCastException - InvalidCastException when sharing data and adding to ObservableCollection 向表添加新项时发生InvalidCastException - InvalidCastException when adding new item to table Code-First:将实体添加到dbset时的空引用异常 - Code-First: Null reference exception when adding an entity to a dbset 当应用程序启动并创建 DbContext 时,将新的 DbSet 添加到 DbContext - Adding new DbSet to DbContext when application has started and DbContext created 在Entify Framework 6中添加DBSet时无法更新数据库消息 - Unable to update database message when adding a DBSet in Entify Framework 6 InvalidCastException对象[*]到Object [] - InvalidCastException Object[*] to Object[] 向EntityFramework DBset添加方法 - Adding methods to EntityFramework DBset 将对象强制转换为整数时,为什么会收到InvalidCastException? - Why am I getting InvalidCastException when casting object to integer? 调用Dictionary.TryGetValue(String,out object)时发生InvalidCastException。 为什么? - InvalidCastException when calling Dictionary.TryGetValue(String, out object). Why? 从Entity.DynamicProxies.MyEntityClass到Entity.DbSet`1 [MyEntityClass]的InvalidCastException - InvalidCastException from Entity.DynamicProxies.MyEntityClass to Entity.DbSet`1[MyEntityClass]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM