A
A
Alexey Alex2014-06-29 21:33:40
ASP.NET
Alexey Alex, 2014-06-29 21:33:40

EF CodeFirst: What causes an error when creating a DB (doesn't want to create)?

Hello. I'm trying to create a database:
There are 2 models:

public class Player
    {
        public int PlayerId { get; set; }
        public int TeamId { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public virtual Team Team { get; set; }
    }
 public class Team
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Coach { get; set; }
        public List<Player> Player { get; set; }
    }

DbEntity class
public class DbEntity : DbContext
    {
        public DbSet<Player> Players { get; set; }
        public DbSet<Team> Teams { get; set; }
    }

Initialization:
Database.SetInitializer(new CreateDatabaseIfNotExists<DbEntity>());

Connection string:
<connectionStrings>
    <add name="DbEntity"
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\Footbal.mdf';Integrated Security=True"
          providerName="System.Data.SqlClient" />
  </connectionStrings>

Well, in the controller, I initialize an object of the DbEntity class.
After starting the application, the database is not created ...
Maybe I'm doing something wrong ... I just recently started getting acquainted with EF, there is little normal documentation ... I turn around ... I look for pieces and try

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri, 2014-06-30
@Gilga

Database.SetInitializer(new CreateDatabaseIfNotExists<DbEntity>());

This is the setting for what to do with the database on the first request.
using (DbEntitycontext = new DbEntity())
            {
                var query = context.Players.ToList();
            }

Explicitly create a database in this way:
using (DbEntitycontext = new DbEntity())
            {
                context.Database.Create();
            }

A
Alexey Gagarin, 2014-07-03
@Alexey_Gagarin

Um... I'm not at all sure that the connection string should be written like this:
MyDatabase - context class name
InitalCatalog=MyDb - database name.
And as correctly written above, to create a database, you need to perform some action with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question