0

I want to create a SQL Server database in .net using Entity Framework, but I can't find how to do it.

As of now I have:

  • A simple project (WCF service) with all the default name
  • A database model

    Database model picture

  • A SQL file which should create the database; I generated it using the model (generate database from model)

  • A service file (.svc)

Code:

public class Service1 : IService1
{
    public Entity1 GetData(int id)
    {
        using (Model1Container ctx = new Model1Container()) {
            try {
                Entity1 entity = ctx.Entity1Set.FirstOrDefault(e => e.Id == id);
                return entity;
            }
            catch (Exception e) {
                Console.WriteLine("CAPTAIN, WE GOT AN ERROR: " + e);
                return null;
            }
        }
    }

    public String PostData(string value)
    {
        using (Model1Container ctx = new Model1Container()){
            Entity1 newEntity = new Entity1();
            newEntity.Property1 = value;
            ctx.Entity1Set.Add(newEntity);

            try {
                ctx.SaveChanges();
            } catch (Exception e) {
                return ("CAPTAIN, WE GOT AN ERROR: " + e); 
            }   
        }
        return "0";
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }

        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

But the problem is that is seems that the database isn't created. I cannot find how to run the SQL file, the server explorer shows nothing, and when I try to do a request in my database I got the following error:

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Entity1Set'.

Did I forgot something important?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Obsidian
  • 25
  • 4

1 Answers1

0

If you are using SQL Server CE, you can tell from your context what to do if the database file does not exists and create the file:

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

If you are using Sqlite, the context is the right place to create the database but that functionality is not fully supported in Entity Framework and you have to do things 'manually'. See here.

If your are dealing with SQL Server or other 'real db' the procedure is similar to this

Community
  • 1
  • 1
Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50