0
votes

I built an Excel importer that is dynamic. Using reflection, its assigning the values to a new instance of an EF object and adding the EF object to the DbSet.

public class Lease
{
    public int Id { get; set; }
    public int StatusId { get; set; }

    public LeaseStatus { get; set; }
}

public class LeaseStatus
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Lease> Leases { get; set; }
}

PROBLEM:

When setting Lease.LeaseStatus property via reflection, I get a System.Data.Entity.Infrastructure.DbUpdateExceptionback when saving the DbSet.

INNER EXCEPTION:

System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Leases_LeaseStatuses". The conflict occurred in database "MyDatabaseName", table "dbo.LeaseStatus", column 'Id'. The statement has been terminated.

QUESTION:

How can I set a navigation property via reflection? If I'm doing it correctly, what may be causing the Exception?

When you get an exception telling you that the insert statement conflicted with a foreign key constraint on the Id column, one possibility you might consider is that maybe the Id value you give it might conflict with the foreign key constraint. But yeah, maybe "foreign key constraint in the database" is a funny way of saying something about reflection. - 15ee8f99-57ff-4f92-890c-b56153
Does it work without reflection? - csharpfolk
add your refelction code how you create the entity and how you attach it to the dbContext - Bassam Alugili
@EdPlunkett Thank you for your passive aggressive and useless response. I'm not providing an Id. If you know anything about reflection you'd better understand the question. I'm setting the Navigation Property of one EF object to another EF object. EF should set the associated Id field. I don't need to. - Paul - Soura Tech LLC
@csharpfolk Yes. If I code it for the specific object reflection is dynamically using, it does work. - Paul - Soura Tech LLC