The data that I entered in the database is not displayed. When the code passes the debager after the line db.Contacts.Add(Contact1); I leave in the console. And then the error comes out:
An unhandled exception of type "System.InvalidOperationException" in EntityFramework.dll
Additional information: The context cannot be used while the model is being created. This can be a thrown path. Note: There are no rules for safeguarding.
Models:
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; } } Database Context:
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>(); //} } The code for interacting with the database context:
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", Email = "1", Id = 0, Phone = "1", Skype = "1", }; ContactInformation ContactInformation2 = new ContactInformation { Another = "2", Email = "2", Id = 0, Phone = "2", Skype = "2", }; ContactInformation ContactInformation3 = new ContactInformation { Another = "3", Email = "3", Id = 0, Phone = "3", Skype = "3", }; 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}", c.Id, c.Name, c.SurName, c.MiddleName, c.Organization, c.Position, c.BirthDate /*c.ContInforms*/); } } //Console.ReadKey(); } } configuration file
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="MyBases" connectionString="data source=(localdb)\MSSQLLocalDB;Initial Catalog=userstore.mdf;Integrated Security=True;" providerName="System.Data.SqlClient"/> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
Integrated Security=True;add in the string here such code:;;MultipleActiveResultSets=true- AK ♦