Seeding tables with one to many relationship EF code first - entity-framework

I'm trying to seed some database tables that have a one to many relationship. Using the code first approach with the Entity Framework. Somehow the foreign keys remain empty in the database table activities, column UserId.
Why isn't this working?
context.Users.AddOrUpdate(
u => u.FirstName,
new User { Id = 1, FirstName = "Trees", Preposition = "de", LastName = "Vries", EmailAddress = "trees#test.com", PhoneNumber = 0684637485, Password = "test123", RoleId = 1 }
);
context.SaveChanges();
context.Activities.AddOrUpdate(
a => a.Name,
new Activity
{
Name = "Metselen van de binnenplaats",
Comment = "Voorbeeld commentaar regel 1.",
Start = DateTime.Now,
End = DateTime.Now.AddHours(5),
},//etc.
);
context.SaveChanges();
var randomActivities = (from s in context.Activities select s).OrderBy(x => Guid.NewGuid()).Take(6).ToList();
context.Users.AddOrUpdate(
u => u.Id,
new User { Id = 1, Activities = randomActivities }
);
context.SaveChanges();
Edit: Solution
After a few hours of wrestling with the code I finally managed to get it all working (without having to add foreign keys to the model classes).
I will share the code and some discoveries so others might benefit from it.
A few things to keep in mind.
Code directly to the context!
This does not work:
List<Activity> randomActivities = (from s in context.Activities select s).OrderBy(x => Guid.NewGuid()).Take(2).ToList(); //Does not work
Works:
List<Activity> randomActivities = context.Activities.OrderBy(x => Guid.NewGuid()).Take(2).ToList();
Only call SaveChanges() when you need to link objects that already need to be in the tables.
context.SaveChanges();
And Finally, you can create the data with a relationship to other tables, simple by adding a new List into it (see code below for details).
The seed method looks like this now:
var users = new List<User>
{
new User
{
FirstName = "Trees",
Preposition = "de",
LastName = "Vries",
EmailAddress = "trees#test.com",
PhoneNumber = 0684637485,
Password = "test123",
Activities =
new List<Activity> { // <-- Like this!
new Activity { Name = "Boren muren in de grote hal 1", Start = DateTime.Now, End = DateTime.Now.AddHours(5) },
new Activity { Name = "Vloer schuren 1", Start = DateTime.Now, End = DateTime.Now.AddHours(1) },
new Activity { Name = "Boren muren in de grote hal 2", Start = DateTime.Now, End = DateTime.Now.AddHours(5) },
new Activity { Name = "Vloer schuren 2", Start = DateTime.Now, End = DateTime.Now.AddHours(1) }
},
Messages =
new List<Message>
{
new Message { Subject = "Test onderwerp van bericht 1", Body = "Tekst van het bericht 1", AuthorId = 3 },
new Message { Subject = "Test onderwerp van bericht 2", Body = "Tekst van het bericht 2", AuthorId = 3 },
new Message { Subject = "Test onderwerp van bericht 3", Body = "Tekst van het bericht 3", AuthorId = 3 }
}
},
new User { FirstName = "Jaap", LastName = "Winter", EmailAddress = "jaap#test.com", PhoneNumber = 0628305643, Password = "test123" },
new User { FirstName = "Klaas", LastName = "Janssen", EmailAddress = "klaas#test.com", PhoneNumber = 0639453321, Password = "test123" }
};
users.ForEach(s => context.Users.AddOrUpdate(r => r.FirstName, s));
context.SaveChanges();
List<Activity> randomActivities = context.Activities.OrderBy(x => Guid.NewGuid()).Take(2).ToList();
var projects = new List<Project>
{
new Project { Name = "Test project", Description = "Omschrijving van test project 1.", Start = DateTime.Now, End = DateTime.Now.AddDays(10), User = context.Users.Single(s => s.FirstName == "Trees"), Activities = randomActivities }
};
projects.ForEach(s => context.Projects.AddOrUpdate(r => r.Name, s));
Activity model class:
public class Activity
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public Skill Skill { get; set; }
public string Comment { get; set; }
}
User model class:
public int Id { get; set; }
public string FirstName { get; set; }
public string Preposition { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public int PhoneNumber { get; set; }
public string Password { get; set; }
public bool Active { get; set; }
public Role Role { get; set; }
public ICollection<Skill> Skills { get; set; }
public ICollection<Message> Messages { get; set; }
public ICollection<Activity> Activities { get; set; }
}

Related

Getting error trying to seed data using EF6 Code First

The models looks like this
public class Account : BaseEntity
{
public string AccountNumber { get; set; }
public string AccountTitle { get; set; }
public decimal CurrentBalance { get; set; }
public AccountStatus AccountStatus { get; set; }
[ForeignKey("UserId")]
public string UserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
}
public enum AccountStatus
{
Active = 0,
InActive = 1
}
public class User : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string ProfilePicUrl { get; set; }
public virtual Account Account { get; set; }
}
public class Transaction : BaseEntity
{
public TransactionType TransactionType { get; set; }
public DateTime TransactionDate { get; set; }
public decimal TransactionAmount { get; set; }
public virtual Account Account { get; set; }
}
public enum TransactionType
{
Deposit = 0,
Withdraw = 1
}
So technically User has One account and Account have one or many Transactions
i am seeding data like below
Basically there are 3 users, 2 of them have accounts associated with them
public class BBBankContext : DbContext
{
public BBBankContext(DbContextOptions<BBBankContext> options) : base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Account> Accounts { get; set; }
public DbSet<Transaction> Transactions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// modelBuilder.Entity<User>()
//.HasOne<Account>(s => s.Account)
//.WithOne(ad => ad.User)
//.HasForeignKey<Account>(ad => ad.UserId);
modelBuilder.Entity<User>(b =>
{
b.HasData(new User
{
Id = "2a2615d0-1c0d-4b9c-b41b-cc01aeb35919",
FirstName = "Raas",
LastName = "Masood",
Email = "admin#patternstech.com",
ProfilePicUrl = "",
});
b.HasData(new User
{
Id = "b6111852-a1e8-4757-9820-70b8c20e1ff0",
FirstName = "Ali",
LastName = "Taj",
Email = "malitaj-dev#outlook.com",
ProfilePicUrl = ""
});
b.HasData(new User
{
Id = "582ebb0b-f9e0-4385-8787-37bd337f18b7",
FirstName = "Salman",
LastName = "Taj",
Email = "salman-dev#outlook.com",
ProfilePicUrl = ""
});
});
modelBuilder.Entity<Account>(b =>
{
b.HasData(new Account
{
Id = "37846734-172e-4149-8cec-6f43d1eb3f60",
AccountNumber = "0001-1001",
AccountTitle = "Ali Taj",
CurrentBalance = 2055M,
AccountStatus = AccountStatus.Active,
UserId = "b6111852-a1e8-4757-9820 -70b8c20e1ff0"
});
b.HasData(new Account
{
Id = "2f115781-c0d2-4f98-a70b-0bc4ed01d780",
AccountNumber = "0002-2002",
AccountTitle = "Salman Taj",
CurrentBalance = 545M,
AccountStatus = AccountStatus.Active,
UserId = "582ebb0b-f9e0-4385-8787-37bd337f18b7"
});
});
modelBuilder.Entity<Transaction>().HasData(
new
{
Id = Guid.NewGuid().ToString(),
AccountId = "37846734-172e-4149-8cec-6f43d1eb3f60",
TransactionAmount = 1000M,
TransactionDate = DateTime.Now,
TransactionType = TransactionType.Deposit
},
new
.....
after adding migration and running "Update-Database" i am getting error
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Accounts_Users_UserId". The conflict occurred in database "BBBankDB", table "dbo.Users", column 'Id'.
Spent many hours tyring to figure this out :( what am i doing wrong ?
I think the problem is you have a wrong UserId in this seed.
b.HasData(new Account
{
Id = "37846734-172e-4149-8cec-6f43d1eb3f60",
AccountNumber = "0001-1001",
AccountTitle = "Ali Taj",
CurrentBalance = 2055M,
AccountStatus = AccountStatus.Active,
UserId = "b6111852-a1e8-4757-9820 -70b8c20e1ff0"
// ^
// Here
});
Remove this additional space and your error will be gone.
UserId = "b6111852-a1e8-4757-9820-70b8c20e1ff0"

How to save list attributes to dbcontext in ASP.Net Core?

I have been trying to store default ApplicationUser data to UserTable instance. However, the data doesn't seem to be stored.
Firstly, UserTable class is as follows:
namespace OA2.Model
{
public class UserTable
{
[Key]
public int UserTableId { get; set; }
public UserTable()
{
ApplicationUsers = new HashSet<ApplicationUser>();
}
[InverseProperty("UserList")]
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
}
I've tried to seed some ApplicationUser data when the project is launched. However, the ApplicationUsers attribute doesn't seem to be saved no matter what I've tried. Here is the code I've tried (with commented segment as well).
public class UserInfoRepository: IUserInfo
{
private readonly PDAContext _context;
public UserInfoRepository(PDAContext context)
{
_context = context;
if (_context.UserTables.Count() == 0)
{
var userTable = new UserTable();
_context.Add(new ApplicationUser { UserList = userTable, Id = "1", UserName = "Taki", Email = "test1#gmail.com", PasswordHash = "password1", UserRole = "Super" });
_context.Add(new ApplicationUser { UserList = userTable, Id = "2", UserName = "Akshdeep", Email = "test2#gmail.com", PasswordHash = "password2", UserRole = "Major" });
_context.Add(new ApplicationUser { UserList = userTable, Id = "3", UserName = "Jin", Email = "test3#gmail.com", PasswordHash = "password3", UserRole = "Senior" });
_context.Add(new ApplicationUser { UserList = userTable, Id = "4", UserName = "Hatfield", Email = "test4#gmail.com", PasswordHash = "password4", UserRole = "Junior" });
_context.Add(new ApplicationUser { UserList = userTable, Id = "5", UserName = "Dooyong", Email = "test5#gmail.com", PasswordHash = "password5", UserRole = "UnAuth" });
_context.SaveChanges();
}
}
Can anyone point out why I'm unable to save db after inserting the user's attributes?
P.S. The following is my ApplicationUser class.
namespace OA2.Domain.Auth
{
public class ApplicationUser : IdentityUser
{
public string UserRole { get; set; }
[ForeignKey("UserList")]
public int UserListId { get; set; }
public virtual UserTable UserList { get; set; }
}
}
I'm using EF 5.0.4.
you have to fix relations
public class UserTable
{
[Key]
public int Id { get; set; }
public UserTable()
{
ApplicationUsers = new HashSet<ApplicationUser>();
}
[InverseProperty(nameof(ApplicationUser.UserTable ))]
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
public class ApplicationUser
{
.... another properties
public int UserTableId {get; set;}
[ForeignKey(nameof(UserTableId ))]
[InverseProperty("ApplicationUsers")]
public virtual UserTable UserTable { get; set; }
}
code
var userTable=new UserTable();
_context.Add(new ApplicationUser { UserTable=userTable, Id = "1", UserName = "Taki", Email = "test1#gmail.com", PasswordHash = "password1", UserRole = "Super" });
_context.Add(new ApplicationUser { UserTable=userTable, Id = "2", UserName = "Akshdeep", Email = "test2#gmail.com", PasswordHash = "password2", UserRole = "Major" });
_context.Add(new ApplicationUser { UserTable=userTable, Id = "3", UserName = "Jin", Email = "test3#gmail.com", PasswordHash = "password3", UserRole = "Senior" });
_context.Add(new ApplicationUser { UserTable=userTable, Id = "4", UserName = "Hatfield", Email = "test4#gmail.com", PasswordHash = "password4", UserRole = "Junior" });
_context.Add(new ApplicationUser { UserTable=userTable, Id = "5", UserName = "Dooyong", Email = "test5#gmail.com", PasswordHash = "password5", UserRole = "UnAuth" });
_context.SaveChanges();

Entity Framework: Is it possible to insert the id of a newly created record into another record while running Seed method

I'm having issues when attempting to use the id created on one record for multiple records.
My models look like this:
public class Student
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StudentId { get; set; }
public int PersonId { get; set; }
public string SID { get; set; }
public int AccountId { get; set; }
public bool Active { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
[ForeignKey("AccountId")]
public virtual Account Account { get; set; }
}
public class Person
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MI { get; set; }
public int SSN { get; set; }
public int AddressId { get; set; }
public int RaceId { get; set; }
[ForeignKey("AddressId")]
public Address Addresss { get; set; }
}
public class Address
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public int ZipCode { get; set; }
}
using the following to seed the database:
context.Students.AddOrUpdate(x => x.SID,
new WestCobb.Data.Student
{
SID = "99-B50-404324175",
EnrollmentDate = Convert.ToDateTime("01-30-2017"),
Active = true,
Person = new WestCobb.Data.Person
{
FirstName = "Brian",
LastName = "Folks",
AddressId = 4,
SSN = 404324175,
Addresss = new WestCobb.Data.Address // This address!
{
StreetAddress = "5076 Lake Charles Court",
City = "Chicago",
State = "Illinois",
ZipCode = 60208
}
},
Account = new WestCobb.Data.Account
{
AccountNumber = "M00000000000088",
AccountTypeId = 1,
Priority = 1,
Rate = 225.00m,
BillingCycleId = 1,
CreateDate = Convert.ToDateTime("01-30-2017"),
Active = true
}
},
// Manually set AddressId of this Person to AddressId of previous Person added
new WestCobb.Data.Student
{
SID = "99-A50-404527896",
EnrollmentDate = Convert.ToDateTime("01-30-2017"),
Active = true,
Person = new WestCobb.Data.Person
{
FirstName = "Arthur",
LastName = "Clue",
SSN = 404527896,
AddressId = context.Addresses.Last().AddressId // This seems not to work
},
Account = new WestCobb.Data.Account
{
AccountNumber = "W89322198433588",
AccountTypeId = 1,
Priority = 2,
Rate = 225.00m,
BillingCycleId = 1,
CreateDate = Convert.ToDateTime("01-30-2017"),
Active = true
}
}
);
and getting the following error:
LINQ to Entities does not recognize the method 'WestCobb.Data.Address Last[Address](System.Linq.IQueryable`1[WestCobb.Data.Address])' method, and this method cannot be translated into a store expression.
Is it possible to use the same "id" (AddressId) that was created from the insertion of the first Person's address in the Address of the second Person? I want to use the same Id for the AddressId of multiple Persons.
If you want to use the same Address entity to multiple Persons, why don't you create the Address first, then use it as many times as you want ?
var myAwesomeAddress = new WestCobb.Data.Address()
{
StreetAddress = "5076 Lake Charles Court",
City = "Chicago",
State = "Illinois",
ZipCode = 60208
};
// You should have a DbSet of your Addresses right ?
context.Addresses.AddOrUpdate(x => x.Id, // Use any discriminator
myAwesomeAddress
);
context.Students.AddOrUpdate(x => x.SID,
new WestCobb.Data.Student
{
SID = "99-B50-404324175",
EnrollmentDate = Convert.ToDateTime("01-30-2017"),
Active = true,
Person = new WestCobb.Data.Person
{
FirstName = "Brian",
LastName = "Folks",
AddressId = 4,
SSN = 404324175,
Addresss = myAwesomeAddress
}
},
new WestCobb.Data.Student
{
SID = "99-A50-404527896",
EnrollmentDate = Convert.ToDateTime("01-30-2017"),
Active = true,
Person = new WestCobb.Data.Person
{
FirstName = "Arthur",
LastName = "Clue",
SSN = 404527896,
Address = myAwesomeAddress // here
}
}
);

What's wrong with my model?

I've created model named Level and now I'm trying to use Seed method to fill a database. Here's a model:
public class Level
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid LevelId { get; set; }
public string Name { get; set; }
[ForeignKey("Course")]
public Guid CourseId { get; set; }
public virtual Course Course { get; set; }
public virtual List<Stage> Stages { get; set; }
}
And here's a piece of Seed method
context.Courses.AddOrUpdate(
c => c.Name,
new Course() { Name = "C# for beginners", LanguageId = context.Languages.FirstOrDefault(k => k.Name == "C#").LanguageId, UserId = context.Users.FirstOrDefault(u => u.Login == "user1").UserId },
new Course() { Name = "Advanced C++", LanguageId = context.Languages.FirstOrDefault(k => k.Name == "C++").LanguageId, UserId = context.Users.FirstOrDefault(u => u.Login == "user2").UserId }
);
context.Levels.AddOrUpdate(
l => l.Name,
new Level() { Name = "Level 1", CourseId = context.Courses.FirstOrDefault(d => d.Name == "C# for beginners").CourseId },
new Level() { Name = "Level 2", CourseId = context.Courses.FirstOrDefault(d => d.Name == "C# for beginners").CourseId },
new Level() { Name = "Level 1", CourseId = context.Courses.FirstOrDefault(d => d.Name == "Advanced C++").CourseId }
);
I have a lot of problems with Levels. One time I had only 2 objects in database instead of 3, now I have
Sequence contains more than one element
error and I don't know why, few minutes ago I've updated database and everything was ok. What's wrong with it?
Thank you

Entity Framework adds a null empty row before the actually row, when adding test data (a reservation)

I have a problem that when adding a reservation, or my test data to the database (using Entity Framework), it created an empty null row in one of the tables.
I have 3 tables
Reservation
ContactPerson
Rooms
There is a many to many relationship between Reservation and Rooms. There is a one to many between ContactPerson and Reservation.
I'm using the code-first approach.
Reservation class:
public class Reservation
{
public Reservation()
{
Room = new List<Room>();
ContactPerson = new ContactPerson();
}
public int ReservationID { get; set; }
public string ReservationNumber { get; set; }
public DateTime CheckInDate { get; set; }
public DateTime CheckOutDate { get; set; }
public int ContactPersonID { get; set; }
public virtual ContactPerson ContactPerson { get; set; }
public virtual ICollection<Room> Room { get; set; }
}
Room class:
public class Room
{
public int ID { get; set; }
public string RoomNumber { get; set; }
public bool Occupied { get; set; }
public bool Smoking { get; set; }
public bool Minibar { get; set; }
public int Beds { get; set; }
public RoomTypeEnum? RoomType { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
public enum RoomTypeEnum
{
Single = 0, Double = 1, Family = 2, Suite = 3
}
ContactPerson class:
public class ContactPerson
{
public int ContactPersonID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public Nationality NationalityType { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
public enum Nationality
{
Denmark, Germany, England, France, Holland, Belgium, Norway, Sweden, Finland
}
My DataContext class:
public interface IDataContext
{
DbSet<Room> Rooms { get; }
DbSet<Reservation> Reservations { get; }
DbSet<ContactPerson> ContactPersons { get; }
int SaveChanges();
void MarkAsModified(Reservation item);
void MarkRoomAsModified(Room item);
void CreateReservation(Reservation item);
}
public class DataContext : DbContext, IDataContext
{
public DataContext() : base("DataContext")
{
}
// DbSet to bookings
public DbSet<Reservation> Reservations { get; set; }
public DbSet<ContactPerson> ContactPersons { get; set; }
public DbSet<Room> Rooms { get; set; }
public void MarkAsModified(Reservation item)
{
Entry(item).State = EntityState.Modified;
}
public void MarkRoomAsModified(Room item)
{
Entry(item).State = EntityState.Modified;
}
public void CreateReservation(Reservation item)
{
Reservations.Add(item);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Reservation>()
.HasMany(c => c.Room).WithMany(i => i.Reservations)
.Map(t => t.MapLeftKey("ReservationID")
.MapRightKey("RoomID")
.ToTable("RoomReservation"));
}
}
I'm inserting test data with the Configuration class that is being generated when you use migrations.
Configuration:
protected override void Seed(WebApplication1.DAL.DataContext context)
{
var reservations = new List<Reservation>
{
new Reservation{ReservationNumber = "123456789", CheckInDate = DateTime.Parse("2016-01-01"), CheckOutDate = DateTime.Parse("2016.01.15"), ContactPersonID = 1
}
};
reservations.ForEach(b => context.Reservations.AddOrUpdate(r => r.ReservationID, b));
context.SaveChanges();
var contactPersons = new List<ContactPerson>
{
new ContactPerson{Title = "Mr" ,FirstName = "Anders",LastName = "Christensen", Email = "AndersChristensen#gmail.com", NationalityType = Nationality.Denmark, PhoneNumber = "44216731" }
};
contactPersons.ForEach(b => context.ContactPersons.AddOrUpdate(c => c.ContactPersonID, b));
context.SaveChanges();
var rooms = new List<Room>
{
new Room {RoomNumber = "101", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = true, Smoking = false},
new Room {RoomNumber = "102", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = true, Smoking = false},
new Room {RoomNumber = "103", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = false, Smoking = false},
new Room {RoomNumber = "104", Beds = 2, RoomType = RoomTypeEnum.Double, Minibar = true, Occupied = false, Smoking = true},
new Room {RoomNumber = "105", Beds = 3, RoomType = RoomTypeEnum.Family, Minibar = true, Occupied = false, Smoking = false},
};
rooms.ForEach(b => context.Rooms.AddOrUpdate(b));
context.SaveChanges();
AddOrUpdateReservation(context, "101", "123456789");
context.SaveChanges();
}
void AddOrUpdateReservation(DataContext context, string roomNumber, string reservationNumber)
{
var reservation = context.Reservations.SingleOrDefault(c => c.ReservationNumber == reservationNumber);
var room = reservation.Room.SingleOrDefault(r => r.RoomNumber == roomNumber);
if (room == null)
reservation.Room.Add(context.Rooms.Single(i => i.RoomNumber == roomNumber));
}
The Reservation table looks good, the Rooms table looks good, too, and the shared table ReservationRoom also looks good. The problem is the ContactPerson table, when I add a room or reservation, it will add an empty row before added the right contact person.
You see it in this screenshot:
Here you see the result just after running commands, add-migration InitialCreate and update-database.
This also happens when trying to add a reservation I have create in my application, when using the method:
public void CreateReservation(Reservation item)
{
Reservations.Add(item);
}
The reservation table look like this:
Here you can see it points to the empty null row that has been created for some reason.
Hope someone can tell me what could be wrong here. I have used days trying to reconfigure the models and stuff, but none have seem to worked for me.
You have this kind of issue because your Reservation constructor implementation is incorrect :
public Reservation()
{
Room = new List<Room>();
ContactPerson = new ContactPerson();
}
Implemented like this, you automatically create a new ContactPerson for the reservation. Then when saving Reservation in your Seed method it will not use the one ContactPerson person you created in that Seed method.
Change your constructor to this :
public Reservation()
{
Room = new List<Room>();
}
Then in your Seed method, because each Reservation must have a ContactPerson you should insert ContactPerson before creating attached Reservation like this :
protected override void Seed(WebApplication1.DAL.DataContext context)
{
var contactPersons = new List<ContactPerson>
{
new ContactPerson{Title = "Mr" ,FirstName = "Anders",LastName = "Christensen", Email = "AndersChristensen#gmail.com", NationalityType = Nationality.Denmark, PhoneNumber = "44216731" }
};
contactPersons.ForEach(b => context.ContactPersons.AddOrUpdate(c => c.ContactPersonID, b));
context.SaveChanges();
var reservations = new List<Reservation>
{
new Reservation{ReservationNumber = "123456789", CheckInDate = DateTime.Parse("2016-01-01"), CheckOutDate = DateTime.Parse("2016.01.15"), ContactPersonID = 1
}
};
reservations.ForEach(b => context.Reservations.AddOrUpdate(r => r.ReservationID, b));
context.SaveChanges();
var rooms = new List<Room>
{
new Room {RoomNumber = "101", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = true, Smoking = false},
new Room {RoomNumber = "102", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = true, Smoking = false},
new Room {RoomNumber = "103", Beds = 1, RoomType = RoomTypeEnum.Single, Minibar = true, Occupied = false, Smoking = false},
new Room {RoomNumber = "104", Beds = 2, RoomType = RoomTypeEnum.Double, Minibar = true, Occupied = false, Smoking = true},
new Room {RoomNumber = "105", Beds = 3, RoomType = RoomTypeEnum.Family, Minibar = true, Occupied = false, Smoking = false},
};
rooms.ForEach(b => context.Rooms.AddOrUpdate(b));
context.SaveChanges();
AddOrUpdateReservation(context, "101", "123456789");
context.SaveChanges();
}
I think also you can call SaveChanges once at the end of your method but for that to work you need to avoid using constant foreign key like you're doing.