Reputation: 48476
I feel like the following code is suboptimal, and that it could be better. I just don't know how to fetch the key without commiting the changes.
var now = DateTime.Now;
var update = new DAL.ServerStatus
{
Accounts = status.Accounts,
Clients = status.Clients,
Created = now,
ServerStarted = status.ServerStarted,
ServerDateTime = status.ServerDateTime
};
var context = DataContext.GetDataContext();
context.ServerStatus.AddObject(update);
context.SaveChanges();
foreach (var character in characters)
{
var characterUpdate = new DAL.ServerOnlineCharacter
{
Account = character.Account,
Alliance = character.Alliance,
Created = now,
Criminal = character.Criminal,
DonationPoints = character.DonationPoints,
EventCredits = character.EventCredits,
FactionTyped = character.FactionTyped,
FactionPoints = character.FactionPoints,
Fame = character.Fame,
GameTime = character.GameTime,
Guild = character.Guild,
GuildAbbreviation = character.GuildAbbreviation,
GuildTitle = character.GuildTitle,
Karma = character.Karma,
Kills = character.Kills,
MapTyped = character.MapTyped,
RaceTyped = character.RaceTyped,
RawName = character.RawName,
Serial = character.Serial,
ServerStatusId = update.Id
};
context.ServerOnlineCharacters.AddObject(characterUpdate);
}
context.SaveChanges();
Ideally I'd want this to be transactional, and not having to go twice to the database to fully commit the changes. How could I achieve this?
This is the method stub by the way:
static void Update(IServerStatusUpdate status, IEnumerable<IServerOnlineCharacterUpdate> characters);
Upvotes: 1
Views: 149
Reputation: 25513
If you have update.Id mapped as a primary key, and there's a relationship mapped between ServerOnlineCharacter and ServerStatus, then you should be able to do
characterUpdate.ServerStatus = update
instead of
characterUpdate.ServerStatusId = update.Id
This would allow you to only need to call context.SaveChanges at the end (and not in the middle).
As far as making the method transactional, EntityFramework abides by TransactionScope, so if you wrap your Update around a TransactionScope and commit it when you're ready, it should execute as you'd expect.
Here's an example of transaction usage
And if you really want to go the extra mile, you might want to take a look at something like AutoMapper to map your interface you're passing into Update to your DAL class. That would reduce a lot of code there.
Upvotes: 2