Reputation: 1625
In CODE FIRST approach,
How to keep the identity columns as wihtout identity seeds (no auto increment) ?
My entity as follow:
public class Product
{
public int Id { get; set; }
...
}
Also, how to do foreign key here ? I want to add foreign key for below object. what are the properties i have to add into above product class ?
public class ProductType
{
public int id { get; set; }
....
}
Thank You
Upvotes: 1
Views: 108
Reputation: 14640
By convention, the default setting is
If the type of the primary key property is numeric or GUID it will be configured as an identity column.
You can change that by providing DatabaseGenerated
attribute and set it as DatabaseGeneratedOption.None
.
To have foreign key from Product
to ProductType
you only need to provide below collection on ProductType
class, it will be automatically discovered by convention, EF will generate foreign key column ProductType_Id
in Products
table.
public ICollection<Product> Products { get; set; }
However, to have both navigation on both classes you can add below code on Product
class.
public int ProductTypeId { get; set; }
public ProductType ProductType { get; set; }
Here is the complete code of the classes.
public class Product
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int ProductTypeId { get; set; }
public ProductType ProductType { get; set; }
}
public class ProductType
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public ICollection<Product> Products { get; set; }
}
Upvotes: 2