为什么我的可为null的int不能为null? EF Core .NET核心

时间:2019-06-28 08:39:16

标签: c# .net oracle entity-framework-core core

我有2张桌子:

public partial class CHILD
{
    public string PID_CHILD { get; set; }    
    public int ID { get; set; }
    public int ID_CHILD { get; set; }
}

public partial class PARENT
{
    public string ID_PARENT { get; set; }
    public int? ID_CHILD { get; set; }
    public List<CHILD> Childs { get; set; }
}

在PARENT中,列ID_CHILD可以为null,但我需要在fluent API中将它们映射在一起:

modelBuilder.Entity<PARENT>(entity =>
{
    entity.HasMany(a => a.Childs)
            .WithOne()
            .HasPrincipalKey(a => a.ID_CHILD)
            .HasForeignKey(b => b.ID_CHILD);
}

但是当我这样做时:

var test = context.PARENT.ToList();

我遇到此错误:

An unhandled exception occurred while processing the request.
InvalidCastException: La colonne contient des données NULL (Column contain null data)
Oracle.ManagedDataAccess.Client.OracleDataReader.GetInt32(int i)

我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

检查数据库是否为此列允许空值,

您尝试同时创建一对多和一对一的类,尝试更改您的类,例如:

public partial class CHILD
{
    public string PID_CHILD { get; set; }    
    public int ID { get; set; }
    public int ID_PARENT { get; set; }

    [ForeignKey("ID_PARENT")]
    public PARENT Parent {get;set;}
}

public partial class PARENT
{
    public string ID_PARENT { get; set; }
    public List<CHILD> Childs { get; set; }
}

有错误:

public partial class PARENT
{
    public string ID_PARENT { get; set; }
    public int? ID_CHILD { get; set; } (one to one)
    public List<CHILD> Childs { get; set; } (many to one)
}

如果您想多对一,则无需指定ID_CHILD(父类和父表),您已经在CHILD类上完成了此操作,我想在表中 如果您想要一对一,需要像这样:

public partial class PARENT
{
    public string ID_PARENT { get; set; }
    public int? ID_CHILD { get; set; }
    public CHILD Child { get; set; }
}

https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx