C# 实体框架代码优先:理解实体关系(一对多)

C# 实体框架代码优先:理解实体关系(一对多),c#,entity-framework,C#,Entity Framework,我对实体框架相当陌生,只是遇到了一个我不理解的问题 下面是我所做的:我创建了一个类事件: public class Event { public int Id { get; set; } public string Title { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public int AddressId { get; set

我对实体框架相当陌生,只是遇到了一个我不理解的问题

下面是我所做的:我创建了一个类
事件

public class Event
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public int AddressId { get; set; }

    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }
} 
和类
地址

public class Address
{
    public int Id { get; set; }
    public string StreeName { get; set; }
    public string StreetNumber { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }

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

我的数据库如下所示:

我不明白的是,为什么EF为
事件
事件
事件
)和
地址
地址
地址
)创建两个表


我的目标是
事件
只有一个相关的
地址

为什么要有两个dbcontext?试着只使用一个
MyEntitiesContext
,它包含
DbSet
DbSet
事件和地址?我想获取和编辑地址以及所有其他实体,这就是为什么我创建了两个DBContext。但也许我错了?我要试试看!正如marc_s所说,试着只在dbcontext上使用。每个模型,而不是每个表,都应该使用一个
dbcontext
。您当前的代码使用不同的表集设置了两个不同的模型。
public class EventContext : DbContext
{
    public EventContext(DbContextOptions<EventContext> options) : base(options)
    {
    }

    public DbSet<Event> Event { get; set; }
}
public class AddressContext : DbContext
{
    public AddressContext(DbContextOptions<AddressContext> options) : base(options)
    {
    }

    public DbSet<Address> Addresses { get; set; }
}
Update-Database -Context EventContext
Update-Database -Context AddressContext