locked
EF core help with Anonymous ttypes RRS feed

  • Question

  • Hello,

    I have the following problem with EF core. A gridview (winforms) is bound to a list  so the users could add or modify data.

     NorthwindContext db;
    
    
            private List<Order> GetOrders()
    
            {
                db = new NorthwindContext();
    
                return db.Orders.Include(x => x.OrderDetails)
                    .Include(c => c.Customer).ToList();
    
            }

    This works fine. Now, I need to "extend" or "attach" or whatever is called additional fields to this, some are coming from scalar functions, returning a string, some are from other tables that do not have navigation properties with the main one. This is not a problem with a Select New statement, however then I get an object of anonymous type which cannot be edited or modified. The columns added could be ReadOnly without  a problem, but the main table as in this example Order should remain open for modification. This is quite simple with ADO, but with EF I'm very confusing. Can someone give a workaround, I"m still learning EF 

    Sample code is from Northwind DB, since my project is large but the goal I'm after is the same. If the code is needed I could attach it. 

    Thanks

    Saturday, July 4, 2020 11:35 PM

Answers

  • Look at the following method GetProducts which uses a public static DbContext and that Products class/model implements INotifyPropertyChanged (important) then in the form a custom BindingList is used. This pattern allows when an edit is done the change is seen by the ChangeTracker of the current DbContext so that when SaveChanges is called any edits or delete are handled, additions are not done in this code sample but can easily be done too. Note that in the code sample I used a child table for a DataGridViewComboBox which needs special attention seen here.

    Here I make one change and see it work via console logging.



    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Tuesday, July 7, 2020 11:57 AM

All replies

  • You need to use a Linq projection using a custom class.

    https://csharp-station.com/Tutorial/Linq/Lesson02

    You can also use a Linq-2-Entities Join instead of an Include

    https://www.tektutorialshub.com/entity-framework/join-query-entity-framework/

    Sunday, July 5, 2020 1:21 AM
  • Ok, thanks will try to.

    The use of the .Inclue is to get the LEFT Join much easier to those null navigation props instead of  writing the whole query with joins

    Sunday, July 5, 2020 9:42 AM
  • Hello,

    Here is an example of a projection that does not go to the extent you want but may give ideas

    using System;
    using System.Linq.Expressions;
    using DataOperationsEntityFrameworkCore.Models;
    
    namespace DataOperationsEntityFrameworkCore.Projections
    {
        public class CustomerItem
        {
            public int CustomerIdentifier { get; set; }
            public string CompanyName { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int? ContactId { get; set; }
            public string ContactTitle { get; set; }
            public int? CountryIdentifier { get; set; }
            public string CountryName { get; set; }
            public int? ContactTypeIdentifier { get; set; }
    
            public static Expression<Func<Customers, CustomerItem>> Projection
            {
                get
                {
                    return (customers) => new CustomerItem()
                    {
                        CustomerIdentifier = customers.CustomerIdentifier,
                        CompanyName = customers.CompanyName,
                        ContactId = customers.ContactId,
                        ContactTitle = customers.ContactTypeIdentifierNavigation.ContactTitle,
                        FirstName = customers.Contact.FirstName,
                        LastName =  customers.Contact.LastName,
                        CountryIdentifier = customers.CountryIdentifier,
                        CountryName = customers.CountryIdentifierNavigation.Name,
                        ContactTypeIdentifier = customers.CountryIdentifier
                    };
                }
            }
        }
    }

    Usage

    public static async Task<List<CustomerItem>> GetCustomersAsync()
    {
    
        return await Task.Run(async () =>
        {
    
            using (var context = new NorthWindContext())
            {
                return await context.Customers.AsNoTracking().Select(CustomerItem.Projection).ToListAsync();
            }
    
        });
    
    }

    For scalar use scalar function mapping


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, July 5, 2020 11:49 AM
  • Thanks for the example ...is awesome. However when invoking context.Savechanges() nothing happens luckily i can edit the grid. 
    Sunday, July 5, 2020 8:33 PM
  • Hi fullstop,
    >>when invoking context.Savechanges() nothing happens.
    Based on your description, I think that some related code will be very helpful to find out the problem.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 6, 2020 9:17 AM
  • Here is the code. Thanks for any inuput you provide guys ..

    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            
            }
    
            NorthwindContext context;
    
    
            private void PopulateData()
            {
                dataGridView1.DataSource = GetCustomers();
            }
            public  List<CustomerItem> GetCustomers()
            {
                context = new NorthwindContext();
                        return  context.Customers.AsTracking().Select(CustomerItem.Projection).ToList();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                PopulateData();
            }
    
            private void bttSaveData_Click(object sender, EventArgs e)
            {
                if (context.ChangeTracker.HasChanges())
                {
                context.SaveChanges();
                MessageBox.Show("Changes are saved");
                }
                    
                else
                {
                    MessageBox.Show("Changes are NOT saved");
                }
            }
        }
    
        public class CustomerItem
        {
            public string CustomerId { get; set; }
            public string CompanyName { get; set; }
            public string ContactName { get; set; }
            public string ContactTitle { get; set; }
            public int? OrdersCount { get; set; }
            
            public static Expression<Func<Customer, CustomerItem>> Projection
            {
                get
                {
                    return (customers) => new CustomerItem()
                    {
                        CustomerId = customers.CustomerId,
                        CompanyName = customers.CompanyName,
                        ContactName = customers.ContactName,
                        ContactTitle = customers.ContactTitle,
                        OrdersCount = customers.Orders.Count()
                        
                    };
                }
            }
        }
    }

    context

     public partial class NorthwindContext : DbContext
        {
            public NorthwindContext()
            {
            }
    
            public NorthwindContext(DbContextOptions<NorthwindContext> options)
                : base(options)
            {
            }
    
            public virtual DbSet<AlphabeticalListOfProduct> AlphabeticalListOfProducts { get; set; }
            public virtual DbSet<Category> Categories { get; set; }
            public virtual DbSet<CategorySalesFor1997> CategorySalesFor1997s { get; set; }
            public virtual DbSet<CurrentProductList> CurrentProductLists { get; set; }
            public virtual DbSet<Customer> Customers { get; set; }
            public virtual DbSet<CustomerAndSuppliersByCity> CustomerAndSuppliersByCities { get; set; }
            public virtual DbSet<CustomerCustomerDemo> CustomerCustomerDemos { get; set; }
            public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
            public virtual DbSet<Employee> Employees { get; set; }
            public virtual DbSet<EmployeeTerritory> EmployeeTerritories { get; set; }
            public virtual DbSet<Invoice> Invoices { get; set; }
            public virtual DbSet<Order> Orders { get; set; }
            public virtual DbSet<OrderDetail> OrderDetails { get; set; }
            public virtual DbSet<OrderDetailsExtended> OrderDetailsExtendeds { get; set; }
            public virtual DbSet<OrderSubtotal> OrderSubtotals { get; set; }
            public virtual DbSet<OrdersQry> OrdersQries { get; set; }
            public virtual DbSet<Product> Products { get; set; }
            public virtual DbSet<ProductSalesFor1997> ProductSalesFor1997s { get; set; }
            public virtual DbSet<ProductsAboveAveragePrice> ProductsAboveAveragePrices { get; set; }
            public virtual DbSet<ProductsByCategory> ProductsByCategories { get; set; }
            public virtual DbSet<QuarterlyOrder> QuarterlyOrders { get; set; }
            public virtual DbSet<Region> Regions { get; set; }
            public virtual DbSet<SalesByCategory> SalesByCategories { get; set; }
            public virtual DbSet<SalesTotalsByAmount> SalesTotalsByAmounts { get; set; }
            public virtual DbSet<Shipper> Shippers { get; set; }
            public virtual DbSet<SummaryOfSalesByQuarter> SummaryOfSalesByQuarters { get; set; }
            public virtual DbSet<SummaryOfSalesByYear> SummaryOfSalesByYears { get; set; }
            public virtual DbSet<Supplier> Suppliers { get; set; }
            public virtual DbSet<Territory> Territories { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                    optionsBuilder.UseSqlServer("Data Source=NST\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
                }
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<AlphabeticalListOfProduct>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Alphabetical list of products");
                });
    
                modelBuilder.Entity<Category>(entity =>
                {
                    entity.HasIndex(e => e.CategoryName)
                        .HasName("CategoryName");
                });
    
                modelBuilder.Entity<CategorySalesFor1997>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Category Sales for 1997");
                });
    
                modelBuilder.Entity<CurrentProductList>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Current Product List");
    
                    entity.Property(e => e.ProductId).ValueGeneratedOnAdd();
                });
    
                modelBuilder.Entity<Customer>(entity =>
                {
                    entity.HasIndex(e => e.City)
                        .HasName("City");
    
                    entity.HasIndex(e => e.CompanyName)
                        .HasName("CompanyName");
    
                    entity.HasIndex(e => e.PostalCode)
                        .HasName("PostalCode");
    
                    entity.HasIndex(e => e.Region)
                        .HasName("Region");
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
                });
    
                modelBuilder.Entity<CustomerAndSuppliersByCity>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Customer and Suppliers by City");
    
                    entity.Property(e => e.Relationship).IsUnicode(false);
                });
    
                modelBuilder.Entity<CustomerCustomerDemo>(entity =>
                {
                    entity.HasKey(e => new { e.CustomerId, e.CustomerTypeId })
                        .IsClustered(false);
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
    
                    entity.Property(e => e.CustomerTypeId).IsFixedLength();
    
                    entity.HasOne(d => d.Customer)
                        .WithMany(p => p.CustomerCustomerDemos)
                        .HasForeignKey(d => d.CustomerId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_CustomerCustomerDemo_Customers");
    
                    entity.HasOne(d => d.CustomerType)
                        .WithMany(p => p.CustomerCustomerDemos)
                        .HasForeignKey(d => d.CustomerTypeId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_CustomerCustomerDemo");
                });
    
                modelBuilder.Entity<CustomerDemographic>(entity =>
                {
                    entity.HasKey(e => e.CustomerTypeId)
                        .IsClustered(false);
    
                    entity.Property(e => e.CustomerTypeId).IsFixedLength();
                });
    
                modelBuilder.Entity<Employee>(entity =>
                {
                    entity.HasIndex(e => e.LastName)
                        .HasName("LastName");
    
                    entity.HasIndex(e => e.PostalCode)
                        .HasName("PostalCode");
    
                    entity.HasOne(d => d.ReportsToNavigation)
                        .WithMany(p => p.InverseReportsToNavigation)
                        .HasForeignKey(d => d.ReportsTo)
                        .HasConstraintName("FK_Employees_Employees");
                });
    
                modelBuilder.Entity<EmployeeTerritory>(entity =>
                {
                    entity.HasKey(e => new { e.EmployeeId, e.TerritoryId })
                        .IsClustered(false);
    
                    entity.HasOne(d => d.Employee)
                        .WithMany(p => p.EmployeeTerritories)
                        .HasForeignKey(d => d.EmployeeId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_EmployeeTerritories_Employees");
    
                    entity.HasOne(d => d.Territory)
                        .WithMany(p => p.EmployeeTerritories)
                        .HasForeignKey(d => d.TerritoryId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_EmployeeTerritories_Territories");
                });
    
                modelBuilder.Entity<Invoice>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Invoices");
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
                });
    
                modelBuilder.Entity<Order>(entity =>
                {
                    entity.HasIndex(e => e.CustomerId)
                        .HasName("CustomersOrders");
    
                    entity.HasIndex(e => e.EmployeeId)
                        .HasName("EmployeesOrders");
    
                    entity.HasIndex(e => e.OrderDate)
                        .HasName("OrderDate");
    
                    entity.HasIndex(e => e.ShipPostalCode)
                        .HasName("ShipPostalCode");
    
                    entity.HasIndex(e => e.ShipVia)
                        .HasName("ShippersOrders");
    
                    entity.HasIndex(e => e.ShippedDate)
                        .HasName("ShippedDate");
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
    
                    entity.Property(e => e.Freight).HasDefaultValueSql("((0))");
    
                    entity.HasOne(d => d.Customer)
                        .WithMany(p => p.Orders)
                        .HasForeignKey(d => d.CustomerId)
                        .HasConstraintName("FK_Orders_Customers");
    
                    entity.HasOne(d => d.Employee)
                        .WithMany(p => p.Orders)
                        .HasForeignKey(d => d.EmployeeId)
                        .HasConstraintName("FK_Orders_Employees");
    
                    entity.HasOne(d => d.ShipViaNavigation)
                        .WithMany(p => p.Orders)
                        .HasForeignKey(d => d.ShipVia)
                        .HasConstraintName("FK_Orders_Shippers");
                });
    
                modelBuilder.Entity<OrderDetail>(entity =>
                {
                    entity.HasKey(e => new { e.OrderId, e.ProductId })
                        .HasName("PK_Order_Details");
    
                    entity.HasIndex(e => e.OrderId)
                        .HasName("OrdersOrder_Details");
    
                    entity.HasIndex(e => e.ProductId)
                        .HasName("ProductsOrder_Details");
    
                    entity.Property(e => e.Quantity).HasDefaultValueSql("((1))");
    
                    entity.HasOne(d => d.Order)
                        .WithMany(p => p.OrderDetails)
                        .HasForeignKey(d => d.OrderId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Order_Details_Orders");
    
                    entity.HasOne(d => d.Product)
                        .WithMany(p => p.OrderDetails)
                        .HasForeignKey(d => d.ProductId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Order_Details_Products");
                });
    
                modelBuilder.Entity<OrderDetailsExtended>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Order Details Extended");
                });
    
                modelBuilder.Entity<OrderSubtotal>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Order Subtotals");
                });
    
                modelBuilder.Entity<OrdersQry>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Orders Qry");
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
                });
    
                modelBuilder.Entity<Product>(entity =>
                {
                    entity.HasIndex(e => e.CategoryId)
                        .HasName("CategoryID");
    
                    entity.HasIndex(e => e.ProductName)
                        .HasName("ProductName");
    
                    entity.HasIndex(e => e.SupplierId)
                        .HasName("SuppliersProducts");
    
                    entity.Property(e => e.ReorderLevel).HasDefaultValueSql("((0))");
    
                    entity.Property(e => e.UnitPrice).HasDefaultValueSql("((0))");
    
                    entity.Property(e => e.UnitsInStock).HasDefaultValueSql("((0))");
    
                    entity.Property(e => e.UnitsOnOrder).HasDefaultValueSql("((0))");
    
                    entity.HasOne(d => d.Category)
                        .WithMany(p => p.Products)
                        .HasForeignKey(d => d.CategoryId)
                        .HasConstraintName("FK_Products_Categories");
    
                    entity.HasOne(d => d.Supplier)
                        .WithMany(p => p.Products)
                        .HasForeignKey(d => d.SupplierId)
                        .HasConstraintName("FK_Products_Suppliers");
                });
    
                modelBuilder.Entity<ProductSalesFor1997>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Product Sales for 1997");
                });
    
                modelBuilder.Entity<ProductsAboveAveragePrice>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Products Above Average Price");
                });
    
                modelBuilder.Entity<ProductsByCategory>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Products by Category");
                });
    
                modelBuilder.Entity<QuarterlyOrder>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Quarterly Orders");
    
                    entity.Property(e => e.CustomerId).IsFixedLength();
                });
    
                modelBuilder.Entity<Region>(entity =>
                {
                    entity.HasKey(e => e.RegionId)
                        .IsClustered(false);
    
                    entity.Property(e => e.RegionId).ValueGeneratedNever();
    
                    entity.Property(e => e.RegionDescription).IsFixedLength();
                });
    
                modelBuilder.Entity<SalesByCategory>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Sales by Category");
                });
    
                modelBuilder.Entity<SalesTotalsByAmount>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Sales Totals by Amount");
                });
    
                modelBuilder.Entity<SummaryOfSalesByQuarter>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Summary of Sales by Quarter");
                });
    
                modelBuilder.Entity<SummaryOfSalesByYear>(entity =>
                {
                    entity.HasNoKey();
    
                    entity.ToView("Summary of Sales by Year");
                });
    
                modelBuilder.Entity<Supplier>(entity =>
                {
                    entity.HasIndex(e => e.CompanyName)
                        .HasName("CompanyName");
    
                    entity.HasIndex(e => e.PostalCode)
                        .HasName("PostalCode");
                });
    
                modelBuilder.Entity<Territory>(entity =>
                {
                    entity.HasKey(e => e.TerritoryId)
                        .IsClustered(false);
    
                    entity.Property(e => e.TerritoryDescription).IsFixedLength();
    
                    entity.HasOne(d => d.Region)
                        .WithMany(p => p.Territories)
                        .HasForeignKey(d => d.RegionId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Territories_Region");
                });
    
                OnModelCreatingPartial(modelBuilder);
            }
    
            partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        }

    customer and orders class

      public partial class Customer
        {
            public Customer()
            {
                CustomerCustomerDemos = new HashSet<CustomerCustomerDemo>();
                Orders = new HashSet<Order>();
            }
    
            [Key]
            [Column("CustomerID")]
            [StringLength(5)]
            public string CustomerId { get; set; }
            [Required]
            [StringLength(40)]
            public string CompanyName { get; set; }
            [StringLength(30)]
            public string ContactName { get; set; }
            [StringLength(30)]
            public string ContactTitle { get; set; }
            [StringLength(60)]
            public string Address { get; set; }
            [StringLength(15)]
            public string City { get; set; }
            [StringLength(15)]
            public string Region { get; set; }
            [StringLength(10)]
            public string PostalCode { get; set; }
            [StringLength(15)]
            public string Country { get; set; }
            [StringLength(24)]
            public string Phone { get; set; }
            [StringLength(24)]
            public string Fax { get; set; }
    
            [InverseProperty(nameof(CustomerCustomerDemo.Customer))]
            public virtual ICollection<CustomerCustomerDemo> CustomerCustomerDemos { get; set; }
            [InverseProperty(nameof(Order.Customer))]
            public virtual ICollection<Order> Orders { get; set; }
        }

      public partial class Order
        {
            public Order()
            {
                OrderDetails = new HashSet<OrderDetail>();
            }
    
            [Key]
            [Column("OrderID")]
            public int OrderId { get; set; }
            [Column("CustomerID")]
            [StringLength(5)]
            public string CustomerId { get; set; }
            [Column("EmployeeID")]
            public int? EmployeeId { get; set; }
            [Column(TypeName = "datetime")]
            public DateTime? OrderDate { get; set; }
            [Column(TypeName = "datetime")]
            public DateTime? RequiredDate { get; set; }
            [Column(TypeName = "datetime")]
            public DateTime? ShippedDate { get; set; }
            public int? ShipVia { get; set; }
            [Column(TypeName = "money")]
            public decimal? Freight { get; set; }
            [StringLength(40)]
            public string ShipName { get; set; }
            [StringLength(60)]
            public string ShipAddress { get; set; }
            [StringLength(15)]
            public string ShipCity { get; set; }
            [StringLength(15)]
            public string ShipRegion { get; set; }
            [StringLength(10)]
            public string ShipPostalCode { get; set; }
            [StringLength(15)]
            public string ShipCountry { get; set; }
    
            [ForeignKey(nameof(CustomerId))]
            [InverseProperty("Orders")]
            public virtual Customer Customer { get; set; }
            [ForeignKey(nameof(EmployeeId))]
            [InverseProperty("Orders")]
            public virtual Employee Employee { get; set; }
            [ForeignKey(nameof(ShipVia))]
            [InverseProperty(nameof(Shipper.Orders))]
            public virtual Shipper ShipViaNavigation { get; set; }
            [InverseProperty(nameof(OrderDetail.Order))]
            public virtual ICollection<OrderDetail> OrderDetails { get; set; }
        }

    Monday, July 6, 2020 10:02 AM
  • CustomerItem is not an object of the EF model so it not going to be saved to the database on a SaveChanges().

    You will have to map CustomerItem to one or more EF model objects to save the data to the database.

    Monday, July 6, 2020 11:30 PM
  • hmm isn't mapping done trough this expression, since I get data displayed.

    and if mapping was not there why is data shown at all, this is very confusing must say?

    And the question is how do i do that then..

    public static Expression<Func<Customer, CustomerItem>> Projection { get { return (customers) => new CustomerItem() { CustomerId = customers.CustomerId, CompanyName = customers.CompanyName, ContactName = customers.ContactName, ContactTitle = customers.ContactTitle, OrdersCount = customers.Orders.Count() };

    Tuesday, July 7, 2020 7:14 AM
  • Look at the following method GetProducts which uses a public static DbContext and that Products class/model implements INotifyPropertyChanged (important) then in the form a custom BindingList is used. This pattern allows when an edit is done the change is seen by the ChangeTracker of the current DbContext so that when SaveChanges is called any edits or delete are handled, additions are not done in this code sample but can easily be done too. Note that in the code sample I used a child table for a DataGridViewComboBox which needs special attention seen here.

    Here I make one change and see it work via console logging.



    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Tuesday, July 7, 2020 11:57 AM
  • I thank you EF GODDESS Karen! this is awesome 
    Tuesday, July 7, 2020 12:43 PM
  • hmm  isn't mapping done trough this expression, since I get data dsplayed.

    No the custom object you created for the projection is not part of the EF model,  and all you have done here is created an object, transferred data from the EF object and returned an object that is not associated to EF, which is an independent object not tracked.

    and if mapping was not there why is data shown at all, this is very confusing must say

    You took a custom object, created it, transferred some data to it and displayed the data in the object.

    And the question is how do i do that then.

    One would is a IsDirty flag in the object that was set to true when the object's 'set' was fired for a property.

    Then one can ask the object if it IsDirty to know that the object changed and it may need to be saved to the database.

    Tuesday, July 7, 2020 3:32 PM