Data Annotations
Defining a key to a table in a Model (User Model):
using System.ComponentModel.DataAnnotations;
public class User
{
[Key]
public string Username { get; set; }
public string DisplayName { get; set; }
}
The full list of annotations supported by EF is:
KeyAttribute
StringLengthAttribute
MaxLengthAttribute
ConcurrencyCheckAttribute
RequiredAttribute
TimestampAttribute
ComplexTypeAttribute
ColumnAttribute
TableAttribute
InversePropertyAttribute
ForeignKeyAttribute
DatabaseGeneratedAttribute
NotMappedAttribute
Fluent API
The fluent API is a more advanced way of specifying model configuration that covers everything that data annotations can do in addition to some more advanced configuration not possible with data annotations. Data annotations and the fluent API can be used together.
Letβs say we wanted to rename the column that User.DisplayName is stored in to display_name.:
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.Property(u => u.DisplayName)
.HasColumnName("display_name");
}
}
DbContext
Usually we will craete a derived context, which represents a session with the database, allowing us to query and save data.
using System.Data.Entity;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
Difference between context.add and attach
Add is for adding newly created objects that do not exist in the database.
Attach is for entities that already exist in the database. ( "when you use Attach you tell the context that the entity is already in the database, SaveChanges will have no effect over attached entities." as described here)
More info can be found in this article by Microsoft: Entity Framework Add and Attach and Entity States.
Asp.net MVC - Razor
To allow only logged on users to see some action:
@if (Request.IsAuthenticated)
{
//action
}