public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ProductImage> Images { get; set; }
}
public class ProductImage
{
public int Id { get; set; }
public string ImageName { get; set; }
public string ImageSize { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
Try to always provide enough information. Rather than "Invalid object ProductImage" you likely had something such as "SqlException: Invalid object name "dbo.ProductImage" which better allows to grasp immediately this is a db side table naming isssue
rather than wondering first what could make C# or EF to complain about an "invalid object".
Good point. It seems you are trying to write code by hand for an existing database. You also have the "code first from database" option that could be easier:
Member
16 Points
48 Posts
Invalid object error in EF
Jan 28, 2020 07:33 AM|EngSH|LINK
I want to get product and all its images. but i am getting invalid object error
public class Product { public int Id { get; set; } public string Name { get; set; } public ICollection<ProductImage> Images { get; set; } }
I am getting error "Invalide object ProductImage"
Do i need to create some relationship?
Contributor
4963 Points
4218 Posts
Re: Invalid object error in EF
Jan 28, 2020 08:28 AM|DA924|LINK
What about the 'virtual' keyword?
Member
16 Points
48 Posts
Re: Invalid object error in EF
Jan 28, 2020 08:39 AM|EngSH|LINK
After wasting too much time i found the reason. Table name in DB was ProductImages while model class name was ProductImage
Is there any rules for that?
All-Star
48570 Points
18086 Posts
Re: Invalid object error in EF
Jan 28, 2020 12:24 PM|PatriceSc|LINK
Hi,
This is the default behavior but you can remove this if you want: https://edspencer.me.uk/posts/2012-03-13-entity-framework-plural-and-singular-table-names/
Try to always provide enough information. Rather than "Invalid object ProductImage" you likely had something such as "SqlException: Invalid object name "dbo.ProductImage" which better allows to grasp immediately this is a db side table naming isssue rather than wondering first what could make C# or EF to complain about an "invalid object".
Contributor
4963 Points
4218 Posts
Re: Invalid object error in EF
Jan 28, 2020 04:20 PM|DA924|LINK
Use DB first approach and let EF build the model from the existing DB schema.
All-Star
48570 Points
18086 Posts
Re: Invalid object error in EF
Jan 28, 2020 04:30 PM|PatriceSc|LINK
Good point. It seems you are trying to write code by hand for an existing database. You also have the "code first from database" option that could be easier:
https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/workflows/existing-database#3-reverse-engineer-model (assuming EF6)