DataContext always returns null as foreign key

Marius

we are currently working on a little ASP.NET Page. We're using EntityFramework (EF) and have created a BaseController which handles our DataContext.

Simplified we have 2 Models:

The User-Model (from automatic generated code):

public class User : IdentityUser
    {
        public virtual ICollection<Location> Locations { get; set; }
        public virtual ICollection<Calendar> Calendars { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

And our own Calendar-Model:

 public class Calendar
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        [DataType(DataType.Text)]
        public string GoogleId { get; set; }

        [Required]
        [DataType(DataType.Text)]
        public string Title { get; set; }

        [DataType(DataType.Text)]
        public string Description { get; set; }

        public ICollection<Event> Events { get; set; }
        public User User { get; set; }
    }

So we have the connection between these models with: One User can have many Calendars. But only One Calendar can be from one User.

The following Code is our DataContext:

public class DatabaseContext : IdentityDbContext<User>
{
    public DatabaseContext()
    {
        // ReSharper disable once UnusedVariable
        var instance = SqlProviderServices.Instance;
    }

    public static DatabaseContext Create()
    {
        return new DatabaseContext();
    }

    public DbSet<Location> Locations { get; set; }

    public DbSet<Calendar> Calendars { get; set; }

    public DbSet<Event> Events { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().HasMany(c => c.Calendars);
    }
}

The Problem now is, when I use the DataContext I get everything out of the database. But

DataContext db = new DataContext()
db.Calendar ...

In Calendar the User is always null!

When I adding a Calendar to the Database with ASP.NET MVC in the following Code:

        public ActionResult Create([Bind(Include = "Title,Description")] Models.Calendar calendar)
        {
            if (ModelState.IsValid)
            {
                calendar.User = CurrentUser;
                calendar.Events = new List<Event>();
                Db.Calendars.Add(calendar);
                Db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(calendar);
        }

I debugged this Method and in the first line in the IF it really sets the right user into the calendar. Can anyone tell me, why Calendar.User is always null?

Andrei

The first important thing: the CurrentUser object should be attached to the context when you create a calendar.

I am not sure if you have LazyLoading for context turned on or off but you can always try to query calendar like that:

(using System.Data.Entity;)
Db.Calendars.Include(calendar => calendar.User).Where(...);

or

Db.Calendars.Include("User").Where(...); 

This should force EF to load linked entity from the database. Try this and see if it works for you.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related