What is the behavior of entity framework when a table does not exist yet for an entity?

182 Views Asked by At

We are working with multiple people on a software landscape. And therefore we find it convenient to work in parallel. So the C# code for the entity is being added, while the table definition is being created (db first approach).

My question is, can this MyEntity, and DbSet be added already to the C# code in the context, without EF throwing exceptions, because the DB table is not in the database yet. This would allow the C# code development to continue (creating repository, provider, validations, etc) in the meanwhile. Of course under the condition that the DbSet is not being used in the C# code.

So is EF fine with the DbSet being part of the context, while the table for MyEntity does not exist in the database yet?

1

There are 1 best solutions below

1
On

Yes you can add the entity to the context, without having the table. I verified this with a test project. See the code below. It connects to an existing DB on the local machine. The context is created without any issues. You can even use the Entities property, add an Entity, and SaveChanges(). It will create the table for you the first time. The second time the table is not there (because it got removed manually after creation for instance), it will throw an exception.

It will throw an exception because it keeps records of the state of the database in __MigrationHistory.

    using System.Data.Entity;

namespace EntityFrameWorkMissingTableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new MyContext("Data Source=localhost;Initial Catalog=MyContext;Integrated Security=True"))
            {
                context.Entities.Add(new Entity());
                context.SaveChanges();
            }
        }

        public class MyContext : DbContext
        {
            public MyContext(string connectionString)
                : base(connectionString)
            {

            }

            public DbSet<Entity> Entities { get; set; }
        }

        public class Entity
        {
            public int Id { get; set; }
        }
    }
}