c# LINQ query to select whole object into new?

c# entity-framework-core linq

Question

Not sure if i worded the question correctly, but what im trying to do is return a new viewmodel with one of the parts being a booking:

public class Booking
    {

        public int BookingId { get; set; }
        public int CustomerId { get; set; }

        public Guid UniqueId { get; set; }
        public string EventId { get; set; }
        public bool IsPaid { get; set; }
        public double Price { get; set; }
        public DateTime BookingDate { get; set; }
        public DateTime DateBooked { get; set; }

        [JsonIgnore]
        public Customer Customer { get; set; }

        [JsonIgnore]
        public ICollection<BookingService> BookingServices { get; set; }

        [NotMapped]
        public IEnumerable<Service> Services { get; set; }

    }

and my query is:

            var customers = _dbContext.Customers
                .Select(c => new CustomerBookingsViewModel
                {
                    Customer = c,

                    Bookings = c.Bookings.Select(b => new Booking
                    {
                        BookingId = b.BookingId,
                        BookingDate = b.BookingDate,
                        DateBooked = b.DateBooked,
                        CustomerId = b.CustomerId,
                        UniqueId = b.UniqueId,
                        EventId = b.EventId,
                        IsPaid = b.IsPaid,
                        Price = b.Price,

                        Services = b.BookingServices.Select(s => s.Service)

                    }),
                }
                )
                .ToList();

What I want to know is how to I select all the booking info into the booking without selecting each part, ie:

BookingId = b.BookingId,
BookingDate = b.BookingDate,
DateBooked = b.DateBooked,
CustomerId = b.CustomerId,
UniqueId = b.UniqueId,
EventId = b.EventId,
IsPaid = b.IsPaid,
Price = b.Price,

Can it be done or because the list of services is inside the booking model it cant?

Thanks.

1
2
12/10/2019 9:08:36 AM

Popular Answer

You could implement the IClonable interface on your class.

public class MyClass : ICloneable
{
    public int Id { get; set; }
    public object Clone() => MemberwiseClone();
}

Usage:

var list1 = new List<MyClass> 
{ 
    new MyClass() { Id = 2 }, 
    new MyClass() { Id = 5 } 
};

var list2 = list1.Select(x => (MyClass)x.Clone()).ToList();
list2.First().Id = 10; //list1 won't be affected
2
12/10/2019 9:32:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow