samedi 12 mars 2016

Need help trying to create a one-to-many relationship using EF7, Asp.NET and SQLite

I am new to Entity Framework and Asp.NET, and therefore, struggling with creating database relationships within the Entity Framework.

I have two SQLite tables and have setup my entity models as follows:

public class Users
    {
        [ForeignKey("id")]
        public int id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string email { get; set; }

        public virtual ICollection<Tickets> Tickets { get; set; }
    }

public class Tickets
    {
        public int id { get; set; }
        public string summary { get; set; }
        public string description { get; set; }
        public string c_location { get; set; }
        public string c_store_device { get; set; }
        public string category { get; set; }
        public DateTime? created_at { get; set; }
        public DateTime? closed_at { get; set; }
        public int priority { get; set; }
        public int? assigned_to { get; set; }
        public DateTime? due_at { get; set; }
        public DateTime? updated_at { get; set; }
        public string status { get; set; }

        public virtual Users Users { get; set; }
    }

I am trying to use Entity Framework 7 to export an IEnumerable<Tickets> that includes the User assigned to each Ticket.

I have tried to create my model relationship in MyDBContext as a single User can have multiple Tickets, and also has a foreign key associated in my Sqlite database (Tickets.assigned_to = User.id):

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Users - > many Tickets
        modelBuilder.Entity<Users>()
            .HasMany(p => p.Tickets)
            .WithOne(e => e.Users)
            .HasForeignKey(p => p.assigned_to);
    }

My result ends up with Ticket data being exported, but against every ticket I see a null value for User:

[{"id":10002,...,"Users":null}]

When I use .Include() within my Repository to include each User like this:

public IEnumerable<Tickets> GetAll()
        {
            return _db.Tickets.Include(t => t.Users).ToList();
        }

It results in the error

HTTP Error 502.3 - Bad Gateway The specified CGI application encountered an error and the server terminated the process.

I know it probably has something to do with my relationship model, but I cannot work out what I am doing wrong.

Aucun commentaire:

Enregistrer un commentaire