简体   繁体   中英

EF 6 - One To Many Mapping Always Null

I can't seem to resolve my mapping issue; The relationship is one user may have many venues, A venue must have a user.

My venue class looks like:

public class Venue : BaseObject, IBaseObject
{
    [Required]
    public virtual User Owner { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
}

My User class looks like:

public class User : BaseObject, IBaseObject
{

    [Required]
    public string Name { get; set; }

    [Required]
    [DisplayName("Email")]
    public string EmailAddress { get; set; }

    [Required]
    public string Password { get; set; }

    public bool Active { get; set; }


    public virtual ICollection<Venue> Venues { get; set; } 
}

DbContextClass as requested

 public class SystemContext : DbContext, IDbContext
{
    public SystemContext() :
        base("SystemContext")
    {
        Database.SetInitializer<SystemContext>(null);
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = true;
    }


    public SystemContext(string connectionstringname = "SystemContext") :
        base(connectionstringname)
    {
        Database.SetInitializer<SystemContext>(null);
        Configuration.ProxyCreationEnabled = false;


    }
    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<User>().HasMany(x=>x.Venues);
    }



    public DbSet<PublicQueries> PublicQueries { get; set; }
    public DbSet<Venue> Venues { get; set; }
    public DbSet<User> Users { get; set; }
}

When I load the User class from the database Venues always seems to be null?

I've done something similar before but can't remember how I resoled this.

Thanks

Pretty sure this is a lazy-load issue. If you load an object with navigation properties such as your ICollection<Venues> then they won't be included by default, because they might have more navigation properties linking to more objects, which may have more navigation properties... and before you know it you're loading half the database. This is a particular problem when you've disposed of the context the object came out of by the time you go to access that navigation property, because then it doesn't have a database connection to load them from even if it did realise that it should be doing so.

The fix is to tell Entity Framework that you want that property to be populated, by adding .Include(u => u.Venues); when you get them from the DbSet . You'll need to include System.Data.Entity to get that particular overload of Include() .

You venue class should also have a field called OwnerId .

You can take this link as reference as a start for lazy loading.

public class Venue : BaseObject, IBaseObject
{
    public (int/guid/or other type if you want) OwnerId{get;set;}

    [Required]
    public virtual User Owner { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
}

then also make sure your User class has some Id field which will then be used as foreign Key by EF

This is what I would do,

public class Venue : BaseObject, IBaseObject
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id{get;set;}

    public int OwnerId{get;set;}

    [Required]
    public virtual User Owner { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
}

public class User : BaseObject, IBaseObject
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get;set;}

    [Required]
    public string Name { get; set; }

    [Required]
    [DisplayName("Email")]
    public string EmailAddress { get; set; }

    [Required]
    public string Password { get; set; }

    public bool Active { get; set; }


    public virtual ICollection<Venue> Venues { get; set; } 
}
   public SystemContext() :
        base("SystemContext")
    {
        Database.SetInitializer<SystemContext>(null);
        Configuration.ProxyCreationEnabled = true;
        Configuration.LazyLoadingEnabled = true;
    }

Setting "ProxyCreationEnabled" to true within my context seemes to have solved this issue.

After reading EF 4 - Lazy Loading Without Proxies which quotes:

When using POCO entities with the built-in features of Entity Framework, proxy creation must be enabled in order to use lazy loading. So, with POCO entities, if ProxyCreationEnabled is false, then lazy loading won't happen even if LazyLoadingEnabled is set to true.

check you database,find the forginKey in Venue table,see is it can be null.
if can be null,that is 0..N,if can not be null,that is 1..N
i think you want a 1..N

1..N config with flunt api,use code like

modelBuilder.Entity<User>().HasMany(x=>x.Venues).WithRequired(x=>x.Owner);

if you has a property to save the userid,you can use

modelBuilder.Entity<User>().HasMany(x=>x.Venues).WithRequired(x=>x.Owner).HasForeignKey(x=>x.userid);

or ef will create a db field

these config User,and you can config Venues too

modelBuilder.Entity<Venues>().HasRequired(x=>x.Owner).WithMany(x=>x.Venues).HasForeignKey(x=>x....)

it do same thing

and if you want a 0..N,you can change the HasRequired/WithRequired to HasOptional/WithOptional
the db field can be null

I'm still not sure why this happens (it's probably for better performance...) but you would have to load the property yourself.

So in your case, it would look like this:

// Load the user from the database
User user = await UserDataContext.Users.SingleOrDefaultAsync(u => u.Id == "UserID");

// Then load in all the venues
await UserDataContext.Entry(user).Collection(u => u.Venues).LoadAsync();

// Now you could access the venues
foreach (var venue in user.Venues) Console.WriteLine(venue);

In a one to one mapping situation, simply load the property using the Reference method:

await UserDataContext.Entry(user).Reference(u => u.Venue).LoadAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM