[英]How do I set up a one-to-many relationship using Entity Framework Core?
[英]I am trying to do eager loading using Entity Framework where I have one-to-many relationship between region and client
这是我的Region
model class:
public class Region
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
//navigation property
public virtual ICollection<Client> Clients {get; set;}
}
和我的client
model class:
public class Client
{
[Key]
public Guid Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public virtual Region Regions {get; set;}
public string AlternateNumber { get; set; }
public string Address { get; set; }
public string ImageName { get; set; }
[NotMapped]
public IFormFile ImageFile { get; set; }
[NotMapped]
public string ImageSrc { get; set; }
}
我正在使用 Fluent API 进行关系映射:
builder.Entity<Client>()
.HasOne(c => c.Regions)
.WithMany(x => x.Clients)
.HasForeignKey(c => c.Id);
在这里我需要RegionId
作为外键,但我无法得到它; 我得到的只是ClientId
作为外键。
您必须将 RegionId 列添加到 Client 表
public class Client
{
[Key]
public Guid Id { get; set; }
.....
public Guid RegionId {get; set;}
public virtual Region Region {get; set;}
....
和 dbcontext
modelBuilder.Entity<Client>(entity =>
{
entity.HasOne(d => d.Region)
.WithMany(p => p.Clients)
.HasForeignKey(d => d.RegionId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.