The primary key is defined in model class using key attribute.
eg:-
you need to import system.ComponentModel.DataAnnotations
using system.ComponentModel.DataAnnotations;
public class Customer
{
[key]
public int CustID{get;set;}
public string CustName{get;set;}
}
To create Composite key:
in EF6,key along with column attribute is applied on
multiple properties which will create composite primary key.
using system.ComponentModel.DataAnnotations;
public class Customer
{
[key]
[column(order=1)]
public int CustID{get;set;}
[key]
[column(order=2)]
public int Addressid{get;set;}
public string CustName{get;set;}
}
In the above code,composite primary keys are custid,addressid
Scenario: One customer buys many products.
using system.ComponentModel.DataAnnotations;
public class Customer
{
[key]
public int CustID{get;set;}
public string CustName{get;set;}
public int ProductID { get; set; }
public virtual Products Products{get;set;}
}
public class Products
In the above example, the Customer class includes a reference navigation property of Product class.
So, there can be many products for a single Customer. This will result in a one-to-many relationship between
the Customer and Products table in the database.
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public ICollection
}
ForeignKey Signature: [ForeignKey(name string)]
name :- it is name of the navigation property .From the above example, we can very well say that ProductID is the
foreign key for the Customer table.
You can give your own foreignkey name and that will be created as foreign key in the customer table.
using system.ComponentModel.DataAnnotations;
public class Customer
{
[key]
public int CustID{get;set;}
public string CustName{get;set;}
[Foreignkey("Products")]
public int ProductrefID { get; set; }
public Products Products{get;set;}
}
public class Products
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public ICollection
}
This will create the foreign key column named ProductrefID in the Customer table,
and prevents the generation of a ProductId column in the database.