简体   繁体   中英

Setting up a relationship in Entity Framework Core

I'm trying to set up a one to many relationship in Entity Framework Core using the Fluent API with no success.

I have two objects called Message and Source and are defined as

public class Message
{
    public int ID { get; set; }
    public int FromUserID { get; set; }
    public int ToUserID { get; set; }
    public int SourceID { get; set; }
    public int Priority { get; set; }
    public string Subject { get; set; }
    public string MessageBody { get; set; }
    public DateTime DateTimeCreated { get; set; }
    public DateTime? DateTimeDelivered { get; set; }
    public Source Source { get; set; }
}

public class Source
{
    public int ID { get; set; }
    public string Name { get; set; }
    public ICollection<Message> Messages { get; set; }
}

with one message relating to one source and one source relating to many messages.

In my context class I then have the following

public DbSet<Message> Messages { get; set; }

public DbSet<Source> Sources { get; set; }

and then define the relationship as

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...

    modelBuilder.Entity<Message>()
            .HasOne<Source>(m => m.Source)
            .WithMany(s => s.Messages);

}

If I test this with the following

var get = context.Messages.Where(m => m.ID == 1).FirstOrDefault();

My problem is I get the data returned for the message OK but for source I'm only getting null.

I've looked at different tutorials and SOF questions regarding this, but I can't see where I'm going wrong.

Hope someone can shed some light on this.

There are several ways to load related data:

Eager loading:

means that the related data is loaded from the database as part of the initial query

Explicit loading:

means that the related data is explicitly loaded from the database at a later time

Lazy loading:

means that the related data is transparently loaded from the database when the navigation property is accessed

See the EF Core docs for more information.

If we go with the lazy loading approach, you can set your options with UseLazyLoadingProxies():

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
    .UseLazyLoadingProxies()
    .UseSqlServer(myConnectionString);

...and then make your navigation properties virtual:

public virtual Source Source { get; set; }

and

public virtual ICollection<Message> Messages { get; set; }

Include(msg => msg.Source)添加到查询中,它将强制其加载消息var get = context.Messages.Include(msg => msg.Source).Where(m => m.ID == 1).FirstOrDefault();

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