EF CodeFirst не создаются таблицы + exception
От: DeZhavi Россия  
Дата: 07.02.14 13:25
Оценка:
Добрый день!
Пытаюсь построить таблицы с помощью EF через Code First.
Не получается. Что-то я не так делаю.
Вот код инициализации.
  Database.SetInitializer(new DropCreateDatabaseIfModelChanges<LCCheckpointContext>());
            var db = new LCCheckpointContext(() => { return "LCCheckpointModel";});
            db.Database.Initialize(true);
            var req = new LCRequest { IsFreight = true };
            db.Request.Add(req);
            db.SaveChanges(); 

                var query = from b in db.Request
                            orderby b.Id
                            select b;

                foreach (var item in query)
                {
                    Console.WriteLine(item.Id);
                }

DBContext

  public class LCCheckpointContext : DbContext
    {
           public LCCheckpointContext()
        {

        }
           public LCCheckpointContext(Func<string> nameOrConnectionString)
            : base(nameOrConnectionString())
        {
            Configuration.LazyLoadingEnabled = true;
        }

           protected override void OnModelCreating(DbModelBuilder modelBuilder)
           {
               base.OnModelCreating(modelBuilder);
               modelBuilder.Entity<LCRequest>();
               modelBuilder.Configurations.Add(new RequestConfiguration());

               
           }
       public IDbSet<LCRequest> Request { get; set; }


    }

Один класс модели

  public  class LCRequest 
    {
        public  LCRequest()
        {
   
        }
        [Key]
        public  virtual int Id { get; set; }
        public  virtual bool IsFreight { get; set; }
        public  virtual string FreightDescr { get; set;  }
        public  virtual Guid Barcode { get; set; }

    }

Не создаётся база и в ней таблицы и всё тут.
Вот эксепшен
{"Migrations is enabled for context 'LCCheckpointContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console."}
Собственно, что не так-то? Я уже пол дня мучаюсь, не могу понять что ему надо...
Re: EF CodeFirst не создаются таблицы + exception
От: DeZhavi Россия  
Дата: 07.02.14 13:44
Оценка:
Поробовал сделать вот так:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<LCCheckpointContext, Configuration>());
Вот файлы конфигарции:

    public sealed class Configuration : DbMigrationsConfiguration<LCCheckpointContext>
    {
        public Configuration()
        {
            AutomaticMigrationDataLossAllowed = true;
            AutomaticMigrationsEnabled = true;
            ContextKey = "LCCheckpointContext";
        }
        protected override void Seed(LCCheckpointContext context)
        {

        }
    }

    public class RequestConfiguration : EntityTypeConfiguration<LCRequest>
    {
        public RequestConfiguration()
        {
            ToTable("LCRequests");

        }
    }

Всё равно не работает.
ТОлько ошибка теперь другая
{"Invalid object name 'dbo.LCRequests'."}
Те получается EF не создаёт таблицы, а хочет, что бы они уже были там.
Re: EF CodeFirst не создаются таблицы + exception
От: a11chemist  
Дата: 07.02.14 13:48
Оценка:
Здравствуйте, DeZhavi, Вы писали:

DZ>{"Migrations is enabled for context 'LCCheckpointContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console."}

DZ>Собственно, что не так-то? Я уже пол дня мучаюсь, не могу понять что ему надо...

Посмотри тут http://msdn.microsoft.com/ru-ru/data/jj554735.aspx
Re: Func<string>
От: Loooser Россия  
Дата: 07.02.14 14:00
Оценка:
Здравствуйте, DeZhavi, Вы писали:

DZ>Добрый день!

DZ>
DZ>            var db = new LCCheckpointContext(() => { return "LCCheckpointModel";});
DZ>

DZ>DBContext

DZ>
DZ>  public class LCCheckpointContext : DbContext
DZ>    {
DZ>           public LCCheckpointContext()
DZ>        {

DZ>        }
DZ>           public LCCheckpointContext(Func<string> nameOrConnectionString)
DZ>            : base(nameOrConnectionString())
DZ>        {
DZ>            Configuration.LazyLoadingEnabled = true;
DZ>        }
DZ>    }
DZ>


Извиняюсь за вопрос не по теме: А зачем тут Func<string> вместо обычного string?

PS: так глубоко эту тему не копал, миграцию обходил стороной...
Re[2]: Func<string>
От: DeZhavi Россия  
Дата: 10.02.14 08:12
Оценка:
Здравствуйте, Loooser, Вы писали:

L>Здравствуйте, DeZhavi, Вы писали:


DZ>>Добрый день!

DZ>>
DZ>>            var db = new LCCheckpointContext(() => { return "LCCheckpointModel";});
DZ>>

DZ>>DBContext

DZ>>
DZ>>  public class LCCheckpointContext : DbContext
DZ>>    {
DZ>>           public LCCheckpointContext()
DZ>>        {

DZ>>        }
DZ>>           public LCCheckpointContext(Func<string> nameOrConnectionString)
DZ>>            : base(nameOrConnectionString())
DZ>>        {
DZ>>            Configuration.LazyLoadingEnabled = true;
DZ>>        }
DZ>>    }
DZ>>


L> Извиняюсь за вопрос не по теме: А зачем тут Func<string> вместо обычного string?


L>PS: так глубоко эту тему не копал, миграцию обходил стороной...

Да собсвенно на зачем, для красоты, не придавайте этому значение
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.