Задать вопрос
Ответы пользователя по тегу MySQL
  • Генерация JSON с вложенными объектами

    ap3rus
    @ap3rus
    Слишком мало деталей для ответа на вопрос, потому что существует большое множество ответов — например, воспользоваться ORM, скажем, если вы пишете веб-сервис на .NET, можно воспользоваться Entity Framework или LINQ to SQL:

    public IList<Post> GetPosts(Guid userId)
    {
        using (var context = new DbContext())
        {
            return (from p in context.Posts
                where p.User.Id == userId
                select p).ToList();
        }
    }
    
    //...
    
    public class DbContext: DataContext
    {
        public Table<Post> Posts { return GetTable<Post>(); }
        public Table<User> Users { return GetTable<User>(); }
        public DbContext(string connectionString):base(connectionString) { }
    }
    
    [Table]
    public class Post
    {
        [Column(IsPrimaryKey = true)]
        public int Id { get; set; }
        [Column]private int _userId;
        private EntityRef<User> _user;
        [Association(Storage = "_user", IsForeignKey = true, ThisKey = "Id")]
        public User User
        {
            get { return _user.Entity; }
            set { _user.Entity = value;_userId = value.Id; }
        }
    // ...
    }
    
    [Table]
    public class User
    {
        [Column(IsPrimaryKey = true)]
        public int Id { get; set; }
        
        [Association(OtherKey = "_userId")]private EntitySet<Post> _posts;
    // ...
    }
    
    Ответ написан