Entity Framework Core Default Value Not Loading After Add Range

.net-core entity-framework-core

Question

Net Core 2.0 Entity Framework. When I try to insert data using _context.UserTask.AddRange(userTasks), the TaskID is not being updated after invoking SaveChanges(). Below is the code I'm using.

public partial class UserTask
{
    public Guid TaskID { get; set; }
    public string Text{get;set;}
}

var tasks = taskTexts.Select(s => new UserTask { Text="abc" });

_context.UserTask.AddRange(tasks);
await _context.SaveChangesAsync();

foreach(var n in notifications){
    n.TaskID //This is not returning the actualID inserted on the DB
}

Below is the Table structure

CREATE TABLE dbo.Task(
TaskID [uniqueidentifier] NOT NULL,
[Text] [varchar](200) NOT NULL
 CONSTRAINT [PK_TaskID] PRIMARY KEY CLUSTERED 
 (
TaskID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE  dbo.Task ADD  CONSTRAINT [DF_TaskID]  DEFAULT (newsequentialid()) 
FOR [TaskID]
GO
1
0
8/31/2018 2:56:17 PM

Accepted Answer

What was causing the problem? Enumerables! Take a look at the EDIT section in my question for the solution.

14
2/19/2018 7:14:42 AM

Popular Answer

I'm using Database First in EF 6, and after trying for a period of time, I find a possible solution.

First, Check your Table in the Database, Ensure that you defined the 'ID' column as an auto-increment primary key field, which can be declared by using something like

ID int IDENTITY(1,1) PRIMARY KEY,

when creating your table. Some related information can see here1 or here2.

or you can check the data Properties in MSSQL IDE like:

an img I find in the internet

Second, Set the 'ID' column's StoreGeneratedPattern as Identity, you can do it by open the edmx file in Visual Studio, right click on the Data Column in table and select Properties, and StoreGeneratedPattern setting is in the Properties Window :

enter image description here

Some related article see here.

After complete things above, using EF AddRange, ID will auto increment and all works great.

public class Entity 
{
    public long Id { get; set; }
    public string Field { get; set; }
}

var entities = new Entity[] 
{
    new Entity() { Field = "A" },
    new Entity() { Field = "B" },
};

_dbContext.Entities.AddRange(entities);


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