bubibubi / sqliteef6migrations

System.Data.SQLite.EntityFramework.Migrations - Migrations for SQLite Entity Framework provider
Microsoft Public License
40 stars 20 forks source link

Unable to add foreign key constraint #4

Open LearnGrowAndShare opened 6 years ago

LearnGrowAndShare commented 6 years ago

Hi,

I am having some trouble with the migration to sql lite which has schema defined : Below is my Models

I have below Model"

  public abstract class BaseEntity
    {
        [Key]
        public int Id { get; set; }
    }
public class User: BaseEntity
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }

        public virtual ICollection<Questions> Questions{ get; set; }
    }
  public class Questions: BaseEntity
    {
        public string Details { get; set; }
        public int UserId { get; set; }
        public virtual User User { get; set; }
    }

Db Context

public MyDbContext()
            : base("ConnectionStringName")
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, Configuration>(true));
        }
        public DbSet<User> Users { get; set; }
        public DbSet<Device> Devices { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Configure Code First to ignore PluralizingTableName convention 
            // If you keep this convention then the generated tables will have pluralized names. 
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<Device>()
                .HasRequired<User>(s => s.User)
                .WithMany(g => g.Devices)
                .HasForeignKey<int>(s => s.UserId);
        }

Migration configuration: internal sealed class Configuration : DbMigrationsConfiguration { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; SetSqlGenerator("System.Data.SQLite", new SQLiteMigrationSqlGenerator()); }

I also tried putting ForeignKey attribute, but no luck

Everything comes properly in Database except the foreign key. The relationship is not defined in the sqllite DB.

And for me when I clone this project I was not able to build, was getting some nuget issues, so could not debug or run the example project.

Does below line means its is not supprted: Relationships are not enforced with constraints

Connection string:

bubibubi commented 6 years ago

As you noted, actually relationships are not enforced with contraints on the database. The problem is that EF migration pipeline is written for databases that supports ALTER TABLE ADD CONSTRAINT and is quite tricky to bypass this requirement.

LearnGrowAndShare commented 6 years ago

Any suggestion on how to build this solution/ repo as I am getting quite some error related to nuget pacakge.