1
votes

I am working on Entity Framework 6 and repositories setup to do crud operations. I am trying to insert record in one of the table and getting error for null entries even duo it is not.

{"Cannot insert the value NULL into column 'UI_ID', table 'Blackpool_BPM.dbo.COURSE_INSTANCE'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

enter image description here

The connection to database is correct as I can read data with no problem

At Generic Repository, getting data correctly, just before Save()

enter image description here

Table Structure

enter image description here

Class Model

 [Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
    [Key]
    public int UI_ID { get; set; }

    public string UnitInstanceCode { get; set; }

    public string FESLongDescription { get; set; }

    public string FESShortDescription { get; set; }

    public string FullDescription { get; set; }

    public string OwningOrganisationCode { get; set; }

    public int? OwningOrganisationID { get; set; }

    public string TopicCode { get; set; }

    public string UnitCategory { get; set; }

    public string UnitCode { get; set; }

    public string FESQualificationType { get; set; }

    public int? SCHOOLS { get; set; }

    public int? MARKETING_GROUPS { get; set; }
}

Repository

 public class BIZCourseInstanceRepository : GenericRepository<BIZCourseInstanceEntity>
{
    public BIZCourseInstanceRepository() { }

    public BIZCourseInstanceRepository(DbContext dbContext)
        :base(dbContext)
    { }
}

Unit of work class

  public class BIZ_UOF : IDisposable
{
    private BIZDbContext _BIZDbContextObject = new BIZDbContext();

    protected BIZCourseInstanceRepository _BIZCourseInstanceRepository;

 public BIZCourseInstanceRepository BIZCourseInstanceRepository
    {
        get
        {
            if (this._BIZCourseInstanceRepository == null)
            {
                this._BIZCourseInstanceRepository = new BIZCourseInstanceRepository(_BIZDbContextObject);
            }

            return _BIZCourseInstanceRepository;
        }
    }
    /////

   public void Save()
    {
        _BIZDbContextObject.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

        _BIZDbContextObject.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _BIZDbContextObject.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

DbContext

public class BIZDbContext : BaseContext<BIZDbContext>
{
    public BIZDbContext() : base("_DbContext")
    { }

    public DbSet<BIZCourseInstanceEntity> BIZ_CourseInstance { get; set; }     
}

Generic Repository CRUD

 public void InsertEntity(TEntity obj)
    {
        _DbSet.Add(obj);
    }

Function class where Error is generating at Save()

  public void InsertCourseInstance()
    {
        BIZCourseInstanceEntity BIZCourseInstanceEntityObject = null;

        BIZCourseInstanceEntityObject = new BIZCourseInstanceEntity
        {
            UI_ID = 999999,
            UnitInstanceCode = "KZ999999",
            FESLongDescription = "LONG",
            FESShortDescription = "SHORT",
            FullDescription = "FULL",
            OwningOrganisationCode = "E",
            OwningOrganisationID = 155,
            TopicCode = "04.1",
            UnitCategory = "04",
            UnitCode = "HE-G", 
            FESQualificationType = null,
            SCHOOLS = 5,
            MARKETING_GROUPS = 44

        };

        using (var _uow = new BIZ_UOF())
        {
            _uow.BIZCourseInstanceRepository.InsertEntity(BIZCourseInstanceEntityObject);

            _uow.Save();
        }
    }
2
yes it is null able - Toxic
Just for fun, if you exclude UI_ID, just don't set it to 999999, remove that line. - Johnny
Oh excuses, didn't read well. - user4189129
Do you have any other mapping like Fluent Mapping in your BIZDbContext's or BaseContext's OnModelCreating method where you specify that UI_ID should be an Identity or Computed type? Setting that would exclude it from the generated INSERT sql statement and explain the Exception. - Igor
^--- (continue) -- And I understand you want to force the insert but if the model is set to exclude it based on an erred setting above and the database is configured to not generate a value then the Exception would occur as soon as you try to insert into that table from your EF. The fix is then to correct the model mapping and remove the Identity or Comptuted flag. - Igor

2 Answers

2
votes

You need to tell Entity Framework that your ID is an identity field. If it isn't set up as that in the database, then you need to do that. Otherwise, you'll need to query for the next available ID, and then hope you don't collide with another request trying to save something at the same time.

[Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UI_ID { get; set; }
    ...
}

If you absolutely have to work without any sort of database generated options for your Primary Key, you can instead use the DatabaseGeneratedOption.None value of the enum. This should be avoided to prevent collisions on your PK, but the option does exist.

0
votes

I have found answer, the problem was in my database I am require to provide the Primary key which in my case is UI_ID but in my model I haven't define DatabaseGeneredOption.None, hence throwing error, Thanks for Krillgar guiding me

here is updated model

[Table("COURSE_INSTANCE")]
public class BIZCourseInstanceEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UI_ID { get; set; }

    [StringLength(255)]
    public string UnitInstanceCode { get; set; }

    [StringLength(255)]
    public string FESLongDescription { get; set; }

    [StringLength(255)]
    public string FESShortDescription { get; set; }

    [StringLength(255)]
    public string FullDescription { get; set; }

    [StringLength(255)]
    public string OwningOrganisationCode { get; set; }

    public int? OwningOrganisationID { get; set; }

    [StringLength(255)]
    public string TopicCode { get; set; }

    [StringLength(255)]
    public string UnitCategory { get; set; }

    [StringLength(255)]
    public string UnitCode { get; set; }

    [StringLength(50)]
    public string FESQualificationType { get; set; }

    public int? SCHOOLS { get; set; }

    public int? MARKETING_GROUPS { get; set; }
}