Entity Framework Core assign foreign key constraint in OnModelCreating?

.net-core c# ef-fluent-api entity-framework-core

Question

I'm trying to figure out how to programmatically generate my database using Entity Framework Core and I'm running into issues assigning a foreign key to a field in a table. I need the field Address to reference the Address object and load it when I go to retrieve a record from the database. If I create the database using EnsureCreated, it creates the tables correctly except that the field AddressId is not a foreign key to the Address table. I have tried doing my research on this, and ran into this article, which uses a method called HasForeignKey, however whatever is returning from Entity() doesn't know about HasForeignKey. I get this error if I try manually typing it in I get:

Error CS1061 'EntityTypeBuilder' does not contain a definition for 'HasForeignKey' and no extension method 'HasForeignKey' accepting a first argument of type 'EntityTypeBuilder' could be found (are you missing a using directive or an assembly reference?)

So obviously that approach isn't valid. I tried following this documentation, but I don't really understand what it is doing and how to apply it to my situation. In their case they have a couple tables, blog and posts, where blog has many posts and post has a blog. I tried following along the best I could, but I don't really understand all the jargon and what it is accomplishing.

How can I go about simply assigning the value found in AddressId as a foreign key to a record in Addresses? This is the code I am using.

public class Person
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public byte Age { get; set; }
        public int AddressId { get; set; }
        public Address Address { get; set; }
    }

    public class Address
    {
        [Key]
        public int Id { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }

    public class MyContext: DbContext
    {
        public DbSet<Person> People { get; set; }
        public DbSet<Address> Addresses { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite($"Data Source=test.db");
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<Address>().HasKey(v => v.Id);
            builder.Entity<Person>().HasKey(v => v.Id);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MyContext())
            {
                //var person = db.People.Find(1);

                db.Database.EnsureCreated();

                var person = new Person()
                {
                    FirstName = "Jack",
                    LastName = "Jackson",
                    Age = 50,
                    Address = new Address()
                    {
                        Street = "123 Street St",
                        City = "Jacksonville",
                        State = "Mississippi",
                        ZipCode = "00000-0000"
                    }
                };

                db.People.Add(person);

                db.SaveChanges();
            }
        }
    }

A little extra information:

  • I am using .Net Core 2.0
  • My database is SQLite
  • I am using the Microsoft.EntityFrameworkCore.SQLite & SQLite.Core libraries for my provider.
1
1
7/12/2018 5:27:07 PM

Popular Answer

In your OnModelCreating method try updating the following line to look like this (I wasn't able to test this code so my formatting may be off):

builder.Entity<Person>().HasOne(v => v.Address).HasForeignKey(v => v.AddressId);

I believe that since you have the [Key] Data annotations in both entities, you don't need to set the key up via the Fluent API. Warning - I'm a bit new to EF Core too so I could be wrong. :)

1
7/12/2018 5:10:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow