I would like to have best practice advice in following scenario.
There is a database table called "Product" containing fields "Id,title,category" where "Category" is a foreign key.
In "Product" class , I can implement the same fields as "class attributes" .
public class Product
{
private int id;
private string title;
/*Foreign Key*/
private int categoryId;
public int ID
{
get { return id; }
set { id = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public int CategoryId
{
get { return categoryId; }
set { categoryId = value; }
}
// default constructor
public Product() {
}
}
Is this right approach to make "categoryId" part of Product class and fill this attribute value with Category DTO class from Presentation layer?
You need to separate in your ow n mind how to design tables in a database and how to design classes. They are not the same thing. You need to think about foreign keys in database-design mode, because that's how databases work. There is no such thing as a
foreign key anywhere else in the Universe apart from in a database.
When designing objects, you look at relationships in a different way. A product has a category, so a class that represents a product must include a Category property:
public class Product
{
public int ID {get;set;}
public string Title {get;set;}
public Category Category {get;set;}
}
Member
114 Points
130 Posts
Best Practice Advice
Oct 11, 2014 05:04 PM|developer250|LINK
Hello Community,
I would like to have best practice advice in following scenario.
There is a database table called "Product" containing fields "Id,title,category" where "Category" is a foreign key.
In "Product" class , I can implement the same fields as "class attributes" .
Is this right approach to make "categoryId" part of Product class and fill this attribute value with Category DTO class from Presentation layer?
Saqib
All-Star
194428 Points
28074 Posts
Moderator
Re: Best Practice Advice
Oct 11, 2014 05:58 PM|Mikesdotnetting|LINK
You need to separate in your ow n mind how to design tables in a database and how to design classes. They are not the same thing. You need to think about foreign keys in database-design mode, because that's how databases work. There is no such thing as a foreign key anywhere else in the Universe apart from in a database.
When designing objects, you look at relationships in a different way. A product has a category, so a class that represents a product must include a Category property: