Why my nullable int can't be null ? EF Core .NET CORE

.net c# core entity-framework-core oracle

Question

I have 2 tables :

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; }
}

In PARENT the column ID_CHILD can be null, but I need to map them together in fluent API :

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

But when I do this for example :

var test = context.PARENT.ToList();

I have this error :

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)

What is wrong with my code ?

1
0
6/28/2019 9:22:51 AM

Popular Answer

Check on your database if you allow null values for this column,

your are trying to create a class many to one and one to one at the same time try to change your classes like:

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; }
}

there is the error:

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)
}

You don't need specify the ID_CHILD (Parent class and Parent table) if you want many to one, you already have done this on the CHILD class and I suppose in the table if you want one to one need to be like:

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

1
6/29/2019 6:38:08 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow