我的.Net核心项目中有2个具有一对多关系的模型:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public IEnumerable<Phone> Phone { get; set; }
public User()
{
Phone = new List<Phone>();
}
}
public class Phone
{
public int Id { get; set; }
public string Number { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
在Api控制器中我试图让我的用户包括手机:
public class UserController : Controller
{
private readonly ApplicationDbContext _db;
public UserController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public IEnumerable<User> Get()
{
var users = _db.Users.Include(p => p.Phone).ToArray();
return users;
}
}
但是当我试图在浏览器中调用api / user时,我得到了这个结果:
[{"id":1,"firstName":"Dima","lastName":"Kirsanov","dateOfBirth":"1999-01-01T00:00:00","phone":[{"id":1,"number":"937-99-92","userId":1
因此,json数组不包括具有所有电话号码的所有用户
DbContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Phone> Phones { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new PhoneConfiguration());
modelBuilder.ApplyConfiguration(new UserConfiguration());
base.OnModelCreating(modelBuilder);
}
}
和Fluent Api配置:
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure (EntityTypeBuilder<User> user)
{
user.HasKey(u => u.Id);
user.HasMany(u => u.Phone)
.WithOne(p => p.User)
.HasForeignKey(p => p.UserId);
user.Property(u => u.FirstName)
.IsRequired()
.HasMaxLength(50);
user.Property(u => u.LastName)
.IsRequired()
.HasMaxLength(50);
}
}
public class PhoneConfiguration : IEntityTypeConfiguration<Phone>
{
public void Configure(EntityTypeBuilder<Phone> phone)
{
phone.HasKey(p => p.Id);
phone.Property(p => p.Number)
.IsRequired()
.HasMaxLength(30);
}
}