0

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
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Joe Samraj
  • 311
  • 3
  • 21

1 Answers1

1

Are you sure you're adding a new UserTask, I mean you are getting the task range to add by using a Select function and you are not checking the result. Another thing i don't understand is after call "SaveChanges", you are loopping over a diferent object (notification object VS userTask object), maybe it's something wrong over there.

Try something like this:

        List<UserTask> listToAdd = new List<UserTask>().Add(new UserTask { Text = "NewUserTaskForTest" });

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

        foreach (var userTask in _context.UserTask)
        {
            userTask.TaskID;
            Console.WriteLine(userTask.TaskID.ToString());
        }

I hope help you.

bucyDev
  • 142
  • 8
  • Thanks. mistakenly I put the notification there, I got the issue. The fix is explained here https://stackoverflow.com/questions/42480952/cant-auto-generate-identity-with-addrange-in-entity-framework – Joe Samraj Sep 05 '18 at 06:13