Setting up a relationship in Entity Framework Core

China☆狼群 提交于 2021-01-29 09:55:04

问题


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.


回答1:


Add Include(msg => msg.Source) to the query, and it will force it to load with the message var get = context.Messages.Include(msg => msg.Source).Where(m => m.ID == 1).FirstOrDefault();




回答2:


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; }


来源:https://stackoverflow.com/questions/53225093/setting-up-a-relationship-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!