I am adding a row to a table, MyModel, in a database and then creating a notification regarding that new row to another table. I need the ID of the newly created MyModel row to properly create my notification.
This is my code from my controller:
MyModel newMyModel = new MyModel
{
Title = appliedCourse.Title,
};
db.MyModel.Add();
// I need code here that finds the MyModel.ID - but I do not know how to search for this MyModel
// because MyModel.Title is not necessarily unique - the only necessarily unique piece of data
// would be the MyModel.ID
new MyModel MyModelWithId = db.MyModel.Find(MyModel) // <- that does not work
Notification newNotification = new Notification
{
Time = DateTime.Now,
Link = Url.Action("Details", "MyModel", newMyModelWithId.MyModelID),
ViewableBy = "Admin",
Complete = false
};
db.Notification.Add(newNotification);
db.SaveChanges();
Is there any way to retrieve the newly created MyModel’s ID?
I can think of possibly searching for the ‘largest ID value’ and returning that – but I’m not sure if that’s the most effective way.
Is the ID even created at the point when I need it, or do I need to do a db.SaveChanges(); call before searching for it?
Would it be necessary to add a unique value to the MyModel so that I can query the database for it to acquire it’s ID that way? (although the ID is already my unique value for future queries) I was thinking a DateTimeCreated value and I would search for it like this:
new MyModel MyModelWithId = db.MyModel.FirstOrDefault(
o => o.TimeDateCreated == MyModel.TimeDateCreated);
Not sure if the DateTime method is very efficient either.
You won’t get the ID of the row until after you’ve save the changes.
In your example you’d have to hit SaveChanges twice. Once to save MyModel and generate the ID, then to save newNotification with the URL.Action.
Mind you, unless you’ve got a really compelling reason, I might generate the the Url.Action when the new notification is being displayed and not as part of the model itself. Instead, you could hold a reference and that way only save once. That being said, that’s a rough guess without knowing your use case.