Skip to content

Unable to add foreign key constraint #4

Description

@LearnGrowAndShare

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:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions