I have a simple entity framework 6 code first from existing database project for my web application. When I save data sometimes it saves properly with only 1 record saved. However sometimes it saves 2, 3 5 records it appears random.
For simplicity sake I have the following 2 classes. One is a parent "Person", and "PersonAddress" is the child. In my application there will always be 2 child records to 1 parent. No more no less (dont ask why). Here are my classes which are bare bones.
[Table("Person")]
public partial class Person
{
[Key]
public int PersonID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
[Required]
public virtual ICollection<PersonAddress> PersonAddresses { get; set; }
}
[Table("PersonAddress")]
public partial class PersonAddress
{
[Key]
public int PersonAddressID { get; set; }
public int PersonID { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
}
Here is my DBContext class
public partial class MyDBContext : DbContext
{
public MyDBContext()
: base("name=MyDBContext")
{
//skips database initialization so it wont track changes and produce error, not needed for code first
Database.SetInitializer<MyDBContext>(null);
}
public virtual DbSet<Person> Persons { get; set; }
public virtual DbSet<PersonAddress> PersonAddresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().Property(x => x.PersonID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<PersonAddress>().Property(x => x.PersonAddressID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
//sample code
Person person = new Person();
person.FirstName = "TestFName";
person.LastName = "TestLName";
List<PersonAddress> addresses = new List<PersonAddress>();
PersonAddress address1 = new PersonAddress();
address1.Address1 = "line1"
//etc
//etc
addresses.Add(address1);
PersonAddress address2 = new PersonAddress();
address1.Address2 = "line1"
//etc
//etc
addresses.Add(address2);
//now add addresses to Person
person.PersonAddresses = addresses;
using (var context = new MyDBContext())
{
context.Persons.Add(person);
context.SaveChanges();
obj.PersonID = obj.PersonID;
}
What am I doing wrong, the data always gets saved and the child records are automatically added when I save the parent without issue. But as previously stated sometimes numerous sets of records are saved and I dont see any reason why. Thanks
Try this:
using (var context = new MyDBContext())
{
Person.PersonAdresses.add(addres1);
Person.PersonAdresses.add(addres2);
context.Entry(Person).State=EntityState.Added;
context.SaveChanges();
};
Related
I have two entities:
public class Booking
{
[Key]
public int Id { get; set; }
public int RoomId { get; set; }
[ForeignKey("RoomId")]
public Room Room { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DocumentNumber { get; set; }
public string ContactPhone { get; set; }
}
public class Room
{
[Key]
public int RoomId { get; set; }
public int Number { get; set; }
public int Size { get; set; }
public bool HasBalcony { get; set; }
public int Beds_1 { get; set; }
public int Beds_2 { get; set; }
public double DayPrice { get; set; }
public List<Booking> Bookings { get; set; }
...
public int BookingsCount()
{
return Bookings.Count;
}
public bool IsFree(DateTime dateTime)
{
MessageBox.Show(BookingsCount().ToString());
return true;
}
}
and DbContext:
public class HotelContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<Booking> Bookings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Room)
.WithMany(r => r.Bookings)
.HasForeignKey(b => b.RoomId);
}
}
When MessageBox.Show is called I'm getting exception: An unhandled exception of type 'System.NullReferenceException' occurred in Hotel.exe
When I'm trying to access Room::Bookings, the list is always null. There is one row in Bookings table and multiple rows in Rooms table.
How can I load all of Bookings into Room object?
Depends where you are in the learning curve, however some things stand out
Firstly
You either want to create a relationship via FluentApi or Annotations, not both
Ie. you have this on your Room entity
[ForeignKey("RoomId")]
And this in fluent
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Room)
.WithMany(r => r.Bookings)
.HasForeignKey(b => b.RoomId);
You need to pick one or the other, otherwise you may end-up with multiple Ids in your Booking i.e RoomId and Room_Id
Secondly
If you want to be able to Lazy Load bookings you need to make Bookings collection Virtual
public virtual List<Booking> Bookings { get; set; }
Lastly
To access your data (presuming your connection string is correct)
using(var db = new HoteContext())
{
var rooms = db.Rooms.Include(x => x.Bookings).ToList();
}
Note : Although EF Lazy loads relationships, you might want to make sure you have included the Room->Booking relationship
Consider the following code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (MyDbContext dbContext = new MyDbContext())
{
dbContext.Departments.Add(new Department()
{
Name = "Some Department1",
Employees=new List<Employee>()
{
new Employee() { Name = "John Doe" }
}
});
dbContext.SaveChanges();
var department = dbContext.Departments.FirstOrDefault(d => d.Name == "Some Department1");
if (department.Employees != null)
{
foreach (var item in department.Employees)
{
Console.WriteLine(item.Name);
}
}
}
}
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
}
If you have the code in above way, the control will not go into if condition, because department.Employees is null. Now, change the Department entity as follows.
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Employee> Employees { get; set; }
}
And now you should be able to see control go into if condition and outputs the employees name.
That is called Lazy Loading.
If you want to eagerly load, you don't have to put virtual to the property. You can Include the properties as follows.
var department = dbContext.Departments.Include(d => d.Employees).FirstOrDefault(d => d.Name == "Some Department1");
Now you can see the employees names are getting outputted.
You will absolutely run into performance trouble with your design here.
The temptation with EF is to completely map your object model to the DB and have EF do all the magic for you behind the scenes. But you need to think about it in terms of only getting specifically what you need from the db at any point in time. Otherwise you will get all kinds of cartesian product issues. I highly suggest you get yourself a copy of Hibernating Rhino's EF Profiler or similar so you can analyze your code statically and at runtime for EF performance issues (and see what SQL it is generating). For this what you want is a purpose built call to the DB to get the count. Otherwise what will happen is you will pull the entire table of Bookings and then have C# give you the count. That only makes sense if you want to do something with the whole list. Two options would be:
1) Create a VIEW against the Bookings table and map that to EF. The view would look something like SELECT ROOMS.ROOMID, COUNT(*) - you map this view to your model and voila now you have a list of counts by room (id) and you can use them individually or sum it up to get your total count for all rooms. If you have 1,000 bookings in 10 rooms, you are getting back only 10 rows from the DB. Whereas with your design, you are pulling back all 1,000 bookings with all their fields and then filtering down in C#. Bad juju.
2) The architecturally and conceptually simpler approach is going to be to do a direct query as such (obviously this returns only a single int from the db):
public int BookingsCount()
{
int count = 0;
try
{
using (var context = new HotelContext())
{
var sql ="SELECT COUNT(*) FROM Bookings WHERE ROOMID=" + this.RoomId;
count = context.Database.SqlQuery<int>(sql).First();
}
} catch (Exception ex)
{
// Log your error, count will be 0 by default
}
return count;
}
A simple solution would be making the Bookings property virtual.
public class Room
{
[Key]
public int RoomId { get; set; }
public int Number { get; set; }
public int Size { get; set; }
public bool HasBalcony { get; set; }
public int Beds_1 { get; set; }
public int Beds_2 { get; set; }
public double DayPrice { get; set; }
public virtual List<Booking> Bookings { get; set; }
}
More information on Entity Framework Loading Related Entities,
https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx
So I am dipping into EF Core a little bit and experimenting with inheritance and the TPH pattern (I have no prior experience with this). The resulting database that EF creates is not what I expected and I am wondering if it's possible to get the result I am looking for using fluent-api, or if I am just missing the point altogether.
First, here are my POCO classes:
public class Commission
{
public int Id { get; set; }
public string Description { get; set; }
public double Rate { get; set; }
}
public class Party
{
public int PartyId { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
public class Agency : Party
{
public string AgencyCode { get; set; }
public ICollection<Commission> Commissions { get; set; }
}
public class Carrier : Party
{
public string CarrierCode { get; set; }
public ICollection<Commission> Commissions { get; set; }
}
public class Principal : Party
{
public string Website { get; set; }
public string DistrictCode { get; set; }
}
And my context class just in case:
public class PartyContext : DbContext
{
public DbSet<Agency> Agencies { get; set; }
public DbSet<Carrier> Carriers { get; set; }
public DbSet<Party> Parties { get; set; }
public DbSet<Commission> Commissions { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=LAPTOP-PC\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=True;");
}
}
Basically, Agency, Carrier, and Principal all inherit from Party, so they should have all the same properties as Party. Agency and Carrier have additional specific properties, and should have a zero or one-to-many relationship with Commissions. Additionally, Principal has a couple specific properties, but has no relationship to commissions.
The resulting database is as follows:
I have no issue with the output of the Parties table itself, and understand what the discriminator field is, however I do not understand the two foreign-key relationships it created:
Parties to Commissions_AgencyPartyId
Parties to Commissions_CarrierPartyId
My question is why can't I just have one foreign key relationship from Parties to Commissions_PartyId on the back-end? And if I can, how can I tell EF to create it that way?
EDIT
Using Dmitry's suggestion and using the [InverseProperty] attribute, I ended up with the following database design which is not the desired output:
It actually made a third field (PartyId1). So I started looking at the EF documentation on relationships again and started playing with different annotations. Using the [ForeignKey("PartyId")] attribute gave me some hope after it produced the design that I am expecting:
However, this too had some unexpected effects. After trying to populate the database with an Agency and a Carrier, I receive an exception.
Here's the populating code:
PartyContext _context = new PartyContext();
// Add an Agency
var agencyCommission1 = new Commission
{
Description = "Contract",
Rate = 0.075
};
var agencyCcommission2 = new Commission
{
Description = "Hauling",
Rate = 0.10
};
var agencyCommissionList = new List<Commission>
{
agencyCommission1, agencyCcommission2
};
var agency = new Agency
{
Name = "Agency International",
Address1 = "12345 Main Street",
Address2 = "Suite 100",
City = "Chicago",
State = "IL",
Zip = "31202",
AgencyCode = "AI",
Commissions = agencyCommissionList
};
// Add Carrier
var carrierCommission1 = new Commission
{
Description = "Coal",
Rate = 0.15
};
var carrierCommission2 = new Commission
{
Description = "Mining",
Rate = 0.115
};
var carrierCommissionList = new List<Commission>
{
carrierCommission1, carrierCommission2
};
var carrier = new Carrier
{
Name = "Carrier International",
Address1 = "54321 Main Street",
Address2 = "Suite 300",
City = "Cleveland",
State = "OH",
Zip = "44115",
CarrierCode = "CI",
Commissions = carrierCommissionList
};
_context.Agencies.Add(agency);
_context.Carriers.Add(carrier);
try
{
_context.SaveChanges();
}
catch(Exception ex)
{
return;
}
The exception when adding the Agency is "Unable to cast object of type 'EFTest.Agency' to type 'EFTest.Carrier'." and the exception when trying to add the Carrier is "Unable to cast object of type 'EFTest.Carrier' to type 'EFTest.Agency'."
I will add that when using the original EF design, the program does work as expected, however the additional fields and foreign keys are making my OCD a little crazy :) Any more thoughts are welcome!
If you configure both relationships to use the same property as the foreign key you still have two relationships. So when adding a Commission with PartyIdequal to 1 EF interprets it as being related to an Agency with PartyId equal to 1 and a Carrier with PartyId equal to 1, obviously this would be impossible.
What you would need to do is create a relationship between Commission and Party, however this would mean that the Commissions navigation property would need to be moved to Party as well. But you can still hide it on Principal and other derived classes by making it protected and only exposing it on Agency and Carrier:
public class PartyContext : DbContext
{
public PartyContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Agency> Agencies { get; set; }
public DbSet<Carrier> Carriers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Party>().HasMany(typeof(Commission), "Commissions").WithOne();
}
}
public class Party
{
public int PartyId { get; set; }
protected ICollection<Commission> Commissions { get; set; }
}
public class Agency : Party
{
public new ICollection<Commission> Commissions
{
get { return base.Commissions; }
set { base.Commissions = value; }
}
}
public class Carrier : Party
{
public new ICollection<Commission> Commissions
{
get { return base.Commissions; }
set { base.Commissions = value; }
}
}
public class Commission
{
public int Id { get; set; }
}
Try this:
public class Commission
{
public int Id { get; set; }
public string Description { get; set; }
public double Rate { get; set; }
public Party Party { get; set; } // <-- "parent" party link here
}
public class Agency : Party
{
public string AgencyCode { get; set; }
[InverseProperty("Party")] // <-- link this collection with Party.Party
public ICollection<Commission> Commissions { get; set; }
}
public class Carrier : Party
{
public string CarrierCode { get; set; }
[InverseProperty("Party")] // <-- link this collection with Party.Party
public ICollection<Commission> Commissions { get; set; }
}
Hi i am running into some issues when trying to do an update on a nested collection using Entity Framework. I am using Entity Framework Core but I don't know if that make a difference with this issue.
The application should allow people to be tagged and untagged in a photo.
I am using WebApi and trying to send a patch to update some details but the update doesn't seem to work.
Here is the data model:
Here is my Photo class
public class Photo
{
private Photo() { }
public Photo(string title, string location)
{
CreatedDate = DateTime.UtcNow;
Title = title;
Location = location;
Persons = new HashSet<PersonPhoto>();
}
public int Id { get; set; }
public string Title { get; private set; }
public string Location { get; private set; }
public DateTime CreatedDate { get; private set; }
public ICollection<PersonPhoto> Persons { get; set; }
}
Here is my Person class
public class Person
{
public Person()
{
Photos = new HashSet<PersonPhoto>();
}
public Person(string firstName, string lastName, DateTime dateOfBirth)
{
FirstName = firstName;
LastName = lastName;
DateOfBirth = dateOfBirth;
CreatedDate = DateTime.UtcNow;
}
public int Id { get; set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public DateTime? DateOfBirth { get; private set; }
public DateTime CreatedDate { get; private set; }
public DateTime? LastModified { get; set; }
public ICollection<PersonPhoto> Photos { get; set; }
}
Here is my PersonPhoto class
public class PersonPhoto
{
public int PersonId { get; set; }
public Person Person { get; set; }
public int PhotoId { get; set; }
public Photo Photo { get; set; }
}
I am sending a JsonPatch document containing a PhotoViewModel to the endpoint and I would expect the result to either update or remove a record for the PhotoPerson joining table.
Here is the PhotoViewModel
public class PhotoViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Location { get; set; }
public List<int> Persons { get; set; }
}
Here is the endpoint that I am posting to:
public IActionResult TagPhoto(int id, [FromBody]JsonPatchDocument<PhotoViewModel> patch)
{
// Get Photo first
var photos = _uow.Photos.GetPhoto(id);
var photoVM = Mapper.Map<Photo, PhotoViewModel>(photos);
patch.ApplyTo(photoVM);
var photo = Mapper.Map<PhotoViewModel, Photo>(photoVM);
foreach (var i in photoVM.Persons)
{
photo.Persons.Add(new PersonPhoto()
{
PersonId = i
});
}
_uow.Photos.UpdatePhoto(photo);
_uow.Complete();
return Ok();
}
The mapper that maps a PhotoViewModel to a Photo Entity looks like this:
Mapper.CreateMap<PhotoViewModel, Photo>()
.ForMember(dest => dest.Persons,
opts => opts.Ignore());
The mapper that maps a Photo Entity to a PhotoViewModel looks like this:
Mapper.CreateMap<Photo, PhotoViewModel>()
.ForMember(vm => vm.Persons,
map => map.MapFrom(p => p.Persons.Select(c => c.PersonId)));
and the Repository that handles the data access has this update method:
public void UpdatePhoto(Photo photo)
{
contextTest.Entry(photo).State = EntityState.Modified;
}
Whats currently happening:
If I update the PhotoViewModel properties other than the collection of Persons then the database is updated accordingly. Sql Profiler shows that the update statement contains the new property change (title for example) however when I try to update the nested collection nothing happens in the database and sql profiler has no mention of the nested collection. It just seems to ignore it.
I've tried a few different things. I changed the repository to update like this:
_context.Photos.Update(photo)
This just kept adding new records into the joining table (duplicates too) when I would try to remove from the nested collection nothing would every be removed from the joining table.
Am I missing something really obvious? I've been looking around online but I can't really see a solution for this.
Any help would be very much appreciated!
** Edit **
The _context.SaveChanges() ocurrs in my UnitOfWork here:
public void Complete()
{
_context.SaveChanges();
}
A person can have many colleagues and a colleague is a person. Is it possible to make a clustered key on ColleagueId and PersonId?
Ok, im not really sure but the Colleague class is only there because the database should understand the connection to Person. So, actually i dont need the Colleague class. How can I do so the database understands that the Person has a list of Colleagues that is a Person?
In the program, we can create Persons and then we should be able to add other Persons to the Persons list of Colleagues!
My explanation feels cloudy, but I do not know how to explain it in any other way.
Colleague class:
public class Colleague
{
[Key]
public int ColleagueId { get; set; }
[Key]
public virtual Person PersonId { get; set; }
}
Person class:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public byte[] Image { get; set; }
public virtual ICollection<Conversation> Conversations { get; set; }
public virtual ICollection<Colleague> Colleague { get; set; }
public Person()
{
Conversations = new List<Conversation>();
Colleague = new List<Colleague>();
}
}
I use OrmLite v3 (which does not support complex primary keys). The work around I use there is to create a new property that is a combination of both keys and which I use as a key:
public class Colleague
{
public int ColleagueId { get; set; }
public int PersonId { get; set; }
[Key]
public string CombinedId {
get { return ColleagueId.ToString() + PersonId.ToString(); }
}
}
I use the string type to avoid getting the sum of the two int values (which can lead to key collisions, although is is not completely safe, depending on the int digits numbers). Of course you can adapt this according to your own types.
You basically want a many-to-many relationship between Person entities. For this you would need a junction table which links pairs of Person entities. If we call this entity WorkRelationship:
class WorkRelationship
{
[Key]
[Column(Order = 1)]
[ForeignKey("Myself")]
public int MyselfId { get; set; }
public virtual Person Myself { get; set; }
[Key]
[Column(Order = 2)]
[ForeignKey("Colleague")]
public int ColleagueId { get; set; }
public virtual Person Colleague { get; set; }
}
Then we modify Person like so:
class Person
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Myself")]
public virtual ICollection<WorkRelationship> WorkRelationships { get; set; }
public void AddWorkRelationship(Person colleague)
{
if (WorkRelationships == null)
{
WorkRelationships = new List<WorkRelationship>();
}
WorkRelationships.Add(new WorkRelationship { Myself = this, Colleague = colleague });
}
}
So you can see that Person now has a collection of WorkRelationships: by adding an entity to this collection, you not only link this person to his/her colleague, but also create the inverse relationship. I've also added a helper method so that you can easily add a relationship.
Here's a very basic database context class that can be used to manage these entities:
sealed class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<WorkRelationship> WorkRelationships { get; set; }
public IEnumerable<Person> GetColleagues(int personId)
{
List<WorkRelationship> relationships =
WorkRelationships
.Include(x => x.Myself)
.Include(x => x.Colleague)
.Where(x => x.MyselfId == personId || x.ColleagueId == personId)
.ToList();
foreach (WorkRelationship relationship in relationships)
{
if (relationship.Myself.Id == personId)
{
yield return relationship.Colleague;
}
else if (relationship.Colleague.Id == personId)
{
yield return relationship.Myself;
}
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
}
I've also added a helper method to this that will retrieve the colleagues of a given person.
We can now create a simple test program to insert and query people:
static void Main(string[] args)
{
var alice = new Person { Name = "Alice" };
var bob = new Person { Name = "Bob" };
var colin = new Person { Name = "Colin" };
var davina = new Person { Name = "Davina" };
alice.AddWorkRelationship(bob);
alice.AddWorkRelationship(colin);
bob.AddWorkRelationship(davina);
using (var db = new MyContext())
{
db.People.AddRange(new[] { alice, bob, colin, davina });
db.SaveChanges();
}
using (var db = new MyContext())
{
Console.WriteLine("Bob works with:");
foreach (Person colleague in db.GetColleagues(bob.Id))
{
Console.WriteLine(colleague.Name);
}
}
Console.ReadLine();
}
Original answer below (included for context)
If a Colleague is-a Person, then you should model it like that:
public class Colleague : Person
{
// don't need any other properties based on what you've posted
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public byte[] Image { get; set; }
public virtual ICollection<Conversation> Conversations { get; set; }
public virtual ICollection<Colleague> Colleagues { get; set; }
}
(I have pluralized the property name used to hold the collection of colleagues).
EF Code First should then create a single Person table with an extra Discriminator column used to distinguish between Person and Colleague entities.
Thinking about it a little more, I'm not even sure you need the separate Colleague entity. You could probably get away with this:
public class Person
{
...
public virtual ICollection<Person> Colleagues { get; set; }
}
Note ICollection<Person> instead of ICollection<Colleague>.
I am writing a Data Access Layer using EntityFramework 6. What I want is that when I invoke the SaveChanges() method on the DbContext, it will save the entity together with the set of relevant entities associated via navigation properties. Following is the simple code I am trying to do.
public class Customer
{
public long ID { get; set; }
public string Name { get; set; }
public virtual IEnumberable<PhoneNumber> { get; set; }
}
public class PhoneNumber
{
public long ID { get; set; }
public string Number { get; set; }
}
public class SampleContext : DbContext
{
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<PhoneNumber> PhoneNumbers { get; set; }
}
using(var context = new SampleContext())
{
var customer = new Customer { ID = 1, Name = "John" };
customer.PhoneNumbers = new PhoneNumbers[]
{
new PhoneNumber { ID = 1, Number = "1.111.1111111" },
new PhoneNumber { ID = 2, Number = "1.111.1111112" }
}
context.Customers.Add(customer);
context.SaveChanges();
}
The above code saves the customer in the customers table but saves nothing in the PhoneNumbers table.
Strange but found a solution. The above code need a little modification to make it work. Followings are the modifications:
//In Customer class, changed following line:
public virtual IEnumberable<PhoneNumber> { get; set; }
//To:
public virtual ICollection<PhoneNumber> { get; set; }
//Then in using block initialized entities as follows:
using(var context = new SampleContext())
{
var customer = new Customer { ID = 1, Name = "John", PhoneNumbers = new List<PhoneNumber>() };
customer.PhoneNumbers.Add(new PhoneNumber { ID = 1, Number = "1.111.1111111" });
context.Customers.Add(customer);
context.SaveChanges();
}