Dec182008

LINQ Entity Properties

Let's assume you create an entity class, that represents a structure in your database, for example:
[code:c#]
public class Person 
{
public int PersonID{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
...
}
[/code]
Now after you create this class, you have to tell the compiler that this class represents a table in your database.
Let our table name be PersonsTB. Below is the attribute you have to use:
[code:c#]
[Table(Name="PersonsTB")]//this tells linq that the table for this entity is PersonsTB
public class Person
{
...
}
[/code]
If my class name was exactly the same with the actual table name, then i didnt have to specity the name, i could simply write [Table].
However i used a different class name, so i have to specify the table name as an attribute of the class. What else? All the entity objects
must have a primary key (know why? if you dont have a unique primary key in your entity class, they are readonly, 
you cant modify them, cause datacontext cant keep track of them), lets define our primary key name:
[code:c#]
[Table(Name="PersonsTB")]
public class Person
{
[Column(IsPrimaryKey=true)] public int PersonID{get;set;}
....
}
[/code]
Now our entity class has a table name and a primary key, let's define the other 2 columns. FirstName has the same column name in our table so 
i didnt specify Column Name attribute, but, LastName represents the column SurName in the table, and i did specify a name attribute
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true)] public int PersonID{get;set;}
[Column] public string FirstName{get;set;}
[Column Name="SurName"] public string LastName{get;set;}
...
}
[/code]
Next step is, opps stop, we have a primary key, and usually the primary keys are auto incremented, database generated columns, which means
whenever i insert a value into the table, this primary key will be assigned a value. I want that value to be copied to my primary variable
in the class automatically after the insertion. How? simple just add this attribue:
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true), IsDBGenerated=true] public int PersonID{get;set;}
...
}
[/code]
How about if i assign a value to my entity class's properties and submit the change to the database, however the database has a trigger
or some other way of changing this value before it is submitted!! I also want my entity class properties be synced. Let's assume there is trigger on 
the firstname column, and i want this column to be updated in my entity class after my insertion.
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true), IsDBGenerated=true] public int PersonID{get;set;}
[Column(AutoSync=AutoSync.Insert)] public string FirstName{get;set;}
...
}
[/code]
Confused ? dont be...


Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Add comment