using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test { public class ContactContext : DbContext { public ContactContext() : base("MyBases") { } // Это свойство ссылается на таблицу в базе данных public DbSet<Contact> Contacts { get; set; } public DbSet<ContactInformation> ContInform { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<ContactInformation>().HasRequired(p => p.Contact) .WithMany(b => b.ContInforms) .HasForeignKey(p => p.ContactId); modelBuilder.Ignore<ContactInformation>(); } } public class Contact { [Key] public int Id { get; set; } public string SurName { get; set; } public string Name { get; set; } public string MiddleName { get; set; } public string BirthDate { get; set; } public string Organization { get; set; } public string Position { get; set; } public virtual ICollection<ContactInformation> ContInforms { get; set; } public Contact() { ContInforms = new List<ContactInformation>(); } } public class ContactInformation { public int? ContactId { get; set; } [Key] public int Id { get; set; } public string Phone { get; set; } public string Email { get; set; } public string Skype { get; set; } public string Another { get; set; } public virtual Contact Contact { get; set; } } class Program { static void Main(string[] args) { using (ContactContext db = new ContactContext()) { db.Contacts.Load(); Contact Contact1 = new Contact { Id = 0, Name = "Вася1", SurName = "Пупкин1", MiddleName = "Николаевич1", BirthDate = "1.11.1990", Organization = "Купол1", Position = "programmer1", }; Contact Contact2 = new Contact { Id = 0, Name = "Вася2", SurName = "Пупкин2", MiddleName = "Николаевич2", BirthDate = "1.11.1990", Organization = "Купол2", Position = "programmer2", }; // добавляем их в бд db.Contacts.Add(Contact1); db.Contacts.Add(Contact2); //Contact contact2 = db.Contacts // .Where(o => o.Id == 1) // .FirstOrDefault(); //db.Contacts.Remove(contact2); db.SaveChanges(); ContactInformation ContactInformation1 = new ContactInformation { Another = "1", ContactId = 0, Email = "1", Id = 0, Phone = "1", Skype = "1", Contact = Contact1 }; ContactInformation ContactInformation2 = new ContactInformation { Another = "2", ContactId = 0, Email = "2", Id = 0, Phone = "2", Skype = "2", Contact = Contact1 }; ContactInformation ContactInformation3 = new ContactInformation { Another = "3", //ContactId = 0, Email = "3", //Id = 0, Phone = "3", Skype = "3", Contact = Contact2 }; try { db.ContInform.AddRange(new List<ContactInformation> { ContactInformation1, ContactInformation2, ContactInformation3 }); db.SaveChanges(); Console.WriteLine("Объекты успешно сохранены"); } catch (Exception ex) { Console.WriteLine(ex); } // получаем объекты из бд и выводим на консоль var users = db.Contacts; Console.WriteLine("Список объектов:"); foreach (Contact c in users) { Console.WriteLine("{0}.{1} - {2} - {3} - {4} - {5} - {6} - {7}", c.Id, c.Name, c.SurName, c.MiddleName, c.Organization, c.Position, c.BirthDate, c.ContInforms); } } Console.Read(); } } } 1 answer
Because for EntityFramework you need to fill the ContactId correctly. You write there:
ContactId = 0 Accordingly, that is why there is empty.
After you call the db.SaveChanges(); method db.SaveChanges(); Contact1 and Contact2 assigned their identifiers. In other words, if, after calling this method, you look at their identifiers in debug mode, for example, Contact1.Id , you will see a non-zero identifier there. It will be enough to fill only the ContactId , without filling the Contact property when creating ContactInformation and writing the following:
ContactInformation ContactInformation1 = new ContactInformation { Another = "1", ContactId = Contact1.Id, Email = "1", Id = 0, Phone = "1", Skype = "1" }; And then you will see there is not a zero field.
Or, you can assign a field containing a class object, without assigning an identifier in the form of a foreign key - and then you also get the necessary connection and value, for example:
ContactInformation ContactInformation1 = new ContactInformation { Another = "1", Contact = Contact1, Email = "1", Id = 0, Phone = "1", Skype = "1" }; Also EntityFramework is smart enough to parse and understand nested constructs. For example, if you write like this:
ContactInformation ContactInformation1 = new ContactInformation { Another = "1", Contact = new Contact { Name = "Вася", SurName = "Пупкин", MiddleName = "Николаевич", BirthDate = "1.11.1990", Organization = "Купол", Position = "director", }, Email = "1", Id = 0, Phone = "1", Skype = "1" }; And then call the method of saving changes: db.SaveChanges(); - Objects should be added to the database and the connection between them will be created automatically.
- You shouldn't do this:
ContactId = Contact1.Id, in this caseContact = Contact1! - Pavel Mayorov - @PavelMayorov, I disagree with you. Assigning a value to the property where the identifier is stored is more than sufficient and less resource intensive. - Denis Bubnov
