0

I am using a database-first approach with Entity Framework in .NET Core which ends up using this. Some tables are with a relationship in SQL Server which results joined in code.

I was about to get a DateTime on a joined table and want to give a string format, but to do it I should execute first the query so I could give a format to it like what was mentioned here. The question is, why did the joined table go null after the execution?

To explain my problem easily here's the code:

var a = (from p in db.Product
         select s).ToList();
var b = (from p in a
         select p.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList();
// Brand contains null after execution in "a"

var c = (from p in db.Product
         select p.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList(); 
// Brand contains data but execution gives error due to DateTime.ToString()

In the meantime, This is my solution but I need to create another Model. Which will end up a lot of Model just for this case.

public class ProductBrand 
{
   public class Product { get; set; }
   public class Brand { get; set; }
}
var a = (from s in db.Product
         select new ProductBrand {
             Product = s,
             Brand = s.Brand,
        }).ToList().Select(s => s.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList();

EDITTED:

Above problem was solved by just updating my Model. But problem related to above question still encounter. When saving new Product the Brand becomes null after saving

To explain my problem easily here's the code:

var p = new Product { Name = "temp", BrandId = 1 };
db.Product.Add(p);
db.SaveChanged();
return p.Brand.DateCreated.ToString("MMMM dd, yyyy"); // but Brand is null

In the meantime

var p = new Product { Name = "temp", BrandId = 1 };
db.Product.Add(p);
db.SaveChanged();
if(p.Brand == null) { // Here's my temporary solution, but how about for those tables with lot of joins
   p.Brand = db.Brand.FirstOrDefault(s => s.Id == p.BrandId); 
}
return p.Brand.DateCreated.ToString("MMMM dd, yyyy");

Did I miss something?

Ryan G
  • 71
  • 1
  • 11
  • Why didn't you do the same in var c = db.Product .Select (p=> p.Brand.DateCreated.ToString("MMMM dd, yyyy")).ToList(); ? – Serge Oct 26 '20 at 22:42
  • 1
    And your var c = example is working properly in EF core. What EF are you using? And could you please show your Product and Brand entities? It seems to me that it has the error in a table relations mapping. – Serge Oct 26 '20 at 23:22
  • @Serge thanks for pointing that out. Tried with other tables available and it worked. Only to find out that I need to update my model. Updated the question thou. – Ryan G Oct 29 '20 at 16:59

0 Answers0