Reputation: 77
I have a generic repository where I have a method to save data into database. Knowing that I'm changing an old system, I have faced with this situation:
When I have to save an Area, for example, I need to insert the Id of the field based on the last value inserted inside by database, but for some reason when I try to persist this, an error telling that I can't insert null values into the id of the table appears.
I tried to do this:
areaRepository.Save(new Area{AreaCode = 999, AreaName = "teste"});
areaRepository.SaveAll();
The save method is:
public void Save(T obj)
{
ctx.Set<T>().Add(obj);
}
And the save all method is
public void SaveAll()
{
ctx.SaveChanges();
}
After executing the SaveAll method the error rises.
{"ORA-01400: is not possible to insert null in (\"CELG\".\"EPW_AREAS\".\"AREA_CODE\")\nORA-06512: at line 4"}
Knowing that I'm trying to force the AREA_CODE value, why entity framework doesn't add it and consider the value as null?
Is there a way to force it ?
Does anyone can help ?
Thanks in advice.
Update:
Entity class:
[Table("EPW_AREAS", Schema="CELG")]
public class Area
{
[Key]
[Column("AREA_CODE")]
public int AreCode { get; set; }
[Column("AREA_NAME")]
public string AreName { get; set; }
}
Update 2
Context
public WsContext(string sConnectionString)
: base(sConnectionString)
{
}
public DbSet<Area> Areas { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
Update 3
CREATE TABLE CELG.EPW_AREAS
(
AREA_CODE NUMBER NOT NULL,
AREA_NAME VARCHAR2(30 BYTE)
)
TABLESPACE TBS_CELG_DATA
PCTUSED 0
PCTFREE 10
INITRANS 1
MAXTRANS 255
STORAGE (
INITIAL 64K
NEXT 1M
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0
BUFFER_POOL DEFAULT
)
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;
Upvotes: 0
Views: 1115
Reputation: 15180
The error might occur because Entity Framework is ignoring the value you set for your AreaCode property because it is set up as the Key and by convention EF expects this key to be generated automatically by your DB system.
You can try to disable it as follows:
[Table("EPW_AREAS", Schema="CELG")]
public class Area
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column("AREA_CODE")]
public int AreCode { get; set; }
[Column("AREA_NAME")]
public string AreName { get; set; }
}
Make sure you don't try to add the same area code more than once though.
Upvotes: 4