Некоторые проблемы с отношениями в EF Core - PullRequest
0 голосов
/ 21 мая 2018

В моем проекте .Net Core у меня есть 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 Controller я пытаюсь заставить своих пользователей включать телефоны:

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);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...