Does entity framework throw an exception when a table is not defined while the entity DbSet is defined in the context?

4339 views c#
1

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?

answered question

1 Answer

12

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 after creation), it will throw an exception.

I am not sure why it throws an exception the second time when it needs to recreate the table when it has been deleted.

    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; }
        }
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.