Скрыть атрибут DB при возврате результата Json из DB

#c# #asp.net-mvc

#c# #asp.net-mvc

Вопрос:

Как я могу скрыть скрыть / заменить возврат атрибута как json из db?

В моем случае, если атрибут Download_Link равен null, я не хочу показывать его в json

 var x = db.Books.OrderByDescending(p=>p.Book_id).Take(200).ToList();   
            
            return Json(x.Select(p => new
            {
                Title = p.Book_name,
                ISBN = p.ISBN,
                Edition = p.EditionValue,
                Pages = p.PageCount,
                Authors = p.Author_name,
                Download_Link = p.Pdf_Path_Local.Replace("~","https://s1.bookz.cc")
                
            }
            ), JsonRequestBehavior.AllowGet);
 

Ответ №1:

Я думаю, что единственный способ сделать это — создать два класса

 public class JsonWithoutLink
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public string Edition { get; set; }
        public int Pages { get; set; }
        public string Authors { get; set; }
    }

    public class JsonWithLink : JsonWithoutLink
    {
        public string Download_Link { get; set; }
    }

    public class Book
    {
        public int Book_id { get; set; }
        public string Book_name { get; set; }
        public string ISBN { get; set; }
        public string EditionValue { get; set; }
        public int PageCount { get; set; }
        public string Author_name { get; set; }
        public string Pdf_Path_Local { get; set; }
    }

 

Обратите внимание, что я предполагаю, что класс Book

Далее вам нужно объявить делегат для управления условной логикой

 Func<Book, JsonWithoutLink> ConditionalSelection = delegate (Book b)
        {
            if (string.IsNullOrEmpty(b.Pdf_Path_Local))
            {
                return new JsonWithoutLink
                {
                    Authors = b.Author_name,
                    Edition = b.EditionValue,
                    ISBN = b.ISBN,
                    Pages = b.PageCount,
                    Title = b.Book_name
                };
            }
            else
            {
                return new JsonWithLink
                {
                    Authors = b.Author_name,
                    Edition = b.EditionValue,
                    ISBN = b.ISBN,
                    Pages = b.PageCount,
                    Title = b.Book_name,
                    Download_Link = b.Pdf_Path_Local.Replace("~", "https://s1.bookz.cc")
                };
            }
        };
 

затем в вашем операторе select вам нужно выполнить следующее (в данном случае я использую список, чтобы имитировать контекст)

         public IEnumerable<JsonWithoutLink> get()
        {
            var list = new List<Book>
            {
                new Book
                {
                    Author_name = "Max",
                    Book_id = 1,
                    Book_name = "Book 1",
                    EditionValue = "asdf",
                    ISBN = "1234",
                    PageCount = 3,
                    Pdf_Path_Local = "~/somePath"
                },
                new Book
                {
                    Author_name = "Max",
                    Book_id = 1,
                    Book_name = "Book 1",
                    EditionValue = "asdf",
                    ISBN = "1234",
                    PageCount = 3
                }
            };

            return getJsons(list.AsQueryable().OrderByDescending(b => b.Book_id));
        }
        public  IEnumerable<JsonWithoutLink> getJsons(IOrderedQueryable<Book> books)
        {
            var list =  books
                .Select(ConditionalSelection).ToList();
            return list;
        }
 

Наконец, я убедился, что все правильно