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 ?
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; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.