Sie sind auf Seite 1von 3

Entity Framework Cheat Sheet 1 www.EntityFrameworkTutorial.

net
Working with DbContext Disable lazy loading of navigation properties DataAnnotations Attributes
context.Configuration.LazyLoadingEnabled = false;
Create and use DbContext object [Table(“name”)],
Disable proxy creation of entity [Table(“name”, schema=”name”)]
using (var context = new SchoolContext())
{ context.Configuration.ProxyCreationEnabled = false; Specifies the database table name and schema (optional) that a
//work with context here Disable entity validation class is mapped to.
} [key]
context.Configuration.ValidateOnSaveEnabled = false;
Create Operation Specifies primary key property
context.Students.Add(newStudentObj); [key]
context.SaveChanges(); Default Code-First Conventions [column(Order=1)]
// or
context.Entry(newStudentObj).State = EntityState.Added; Table Name Specifies that a property is one of the key in composite primary key
context.SaveChanges(); <Entity Class Name> + ‘s’ [column(“name”,order=)]
Update Operation Primary key Name [column(“name”,TypeName=)]

context.Entry(updatedObj).State = EntityState.Modified; 1) Id Specifies a database column name, order and data type.
context.SaveChanges(); 2) <Entity Class Name> + ‘Id’ (case insensitive) [timestamp]
Delete Operation Specifies data type of a column as a row version and makes it
e.g. Id or StudentId property becomes primary key of Student by concurrency column. This column will be included in where clause of
context.Entry(entityObj).State = EntityState.Deleted; default
context.SaveChanges(); all updates command. It can be applied to only one property of entity
Foreign key property Name class
Get the current State of an entity
By default EF will look for foreign key property with the same name [ConcurrencyCheck]
var state = context.Entry<Student>(studentObj).State; as principal entity primary key name. Specifies that a property participates in optimistic concurrency
Execute native SQL query for entity types checks. It can be applied to multiple properties of entity class.
If foreign key property does not exists then EF will create FK column
var sList = context.Students.SqlQuery("Select * from in Db table with [Required]
Student").ToList<Student>(); <Dependent Navigation Property Name> + ‘_’ + <Principal Entity Creates NOTNULL column for a property
Execute native SQL query for non-entity types Primary Key Property Name>
[MaxLength(number,Named Parameters)]
string name = context.Database.SqlQuery<string>("Select e.g. EF will create Standard_StandardId foreign key column into [MinLength(number, Named Parameters)]
name from Student ").FirstOrDefault<string>(); Students table if Student entity does not contain foreignkey property Specifies maximum and minimum Length of a string property
Execute native SQL commands for Standard where Standard contains StandardId
[StringLength(number, Named Parameters)]
int noOfRowsAffected = Null column
Specifies the size of a string property
context.Database.ExecuteSqlCommand("CUD command"); EF creates null column for all reference type properties and nullable
[ForeignKey(“name”)]
Explicitly load navigation /reference entity primitive properties
Denotes a property used as a foreign key in a relationship. The
context.Entry(student).Reference(s => NotNull Column
annotation may be placed on the foreign key property and specify
s.Standard).Load(); EF creates NotNull columns for PrimaryKey properties and non- the associated navigation property name, or placed on a navigation
Explicitly Load Collection nullable value type properties property and specify the associated foreign key name.
context.Entry(student).Collection(s => Columns order [NotMapped]
s.Courses).Load(); Move Primary Key properties to appear first in DB table Skips DB column creation for a property
Find by PrimaryKey Properties mapping to DB [InverseProperty(“name”)]
var student = context.Students.Find(1); By default all properties will map to database. Use [NotMapped] Specifies the inverse of a navigation property that represents the
Disable automatic detect changes attribute to exclude property or class from DB mapping other end of the same relationship.
context.Configuration.AutoDetectChangesEnabled = false Cascade delete for One-to-Many [ComplexType]
Enabled by default Specifies complex type.
Entity Framework Cheat Sheet 2 www.EntityFrameworkTutorial.net
DataAnnotations Attributes Fluent API – Property Configuration Fluent API –Property Configurations
[DatabaseGenerated(DatabaseGeneratedOption.Computed)] Set key property Set MaxLength for string column
Sets DB column as computed modelBuilder.Entity<Student>().HasKey(s => modelBuilder.Entity<Student>()
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] s.StudentID); .Property(s => s.StudentName)
Sets DB column as identity Set composite key properties .HasMaxLength(50);
[DatabaseGenerated(DatabaseGeneratedOption.None)] Set fixed length property (char)
modelBuilder.Entity<Student>()
Sets DB column as none .HasKey(s => new { s.StudentID, modelBuilder.Entity<Student>()
s.StudentSubID }); .Property(s => s.StudentName)
Set column order .HasMaxLength(50);
Fluent API – Configure Entity Type
modelBuilder.Entity<Student>() modelBuilder.Entity<Student>()
Entity to Table mapping
.Property(s => s.StudentSubID) .Property(s => s.StudentName)
modelBuilder.Entity<Student>().ToTable("StudentInfo"); .HasColumnOrder(5); .IsFixedLength();
Set DB column datatype Set Unicode string column
modelBuilder.Entity<Student>()
.ToTable("StudentInfo", "dbo"); modelBuilder.Entity<Student>() modelBuilder.Entity<Student>()
.Property(s => s.StudentName) .Property(s => s.StudentName)
Entity splitting into two tables .HasColumnType("varchar"); .IsUnicode();
modelBuilder.Entity<Student>() Set Column name //or
.Map(s => { s.Properties(p => new { p.Id, modelBuilder.Entity<Student>()
p.Name }); modelBuilder.Entity<Student>()
.Property(s => s.StudentName)
s.ToTable("Student"); .Property(s => s.StudentName)
.IsUnicode(false);
}) .HasColumnName("Name");
.Map(s => { s.Properties(p => new { Set decimal column precision
Set parameter name in StoredProcedure
p.Address, p.City}); modelBuilder.Entity<Student>()
s.ToTable("StudentAddress"); modelBuilder.Entity<Student>()
.Property(s => s.Height)
}); .Property(s => s.StudentID)
.HasPrecision(9, 4);
Two entities map to one table
.HasParameterName("Id");
Set Null column Set concurrency property:
modelBuilder.Entity<Student>().ToTable("Student");
modelBuilder.Entity<Student>()
modelBuilder.Entity<Student>()
modelBuilder.Entity<StudentAddress>() .Property(p => p.StudentName)
.Property(s => s.StudentName)
.ToTable("Student"); .IsConcurrencyToken();
.IsOptional();
//or
Configure complex type
Set NotNull column modelBuilder.Entity<Student>()
modelBuilder.ComplexType<Student>(); .Property(p => p.RowVersion)
modelBuilder.Entity<Student>()
.IsRowVersion();
Entity should not mapped with DB table .Property(s => s.StudentName)
.IsRequired(); Set Identity Column
modelBuilder.Ignore<Student>();
modelBuilder.Entity<Student>()
.Property(p => p.StudentID)
.HasDatabaseGeneratedOption(
DatabaseGeneratedOption.Identity);
Entity Framework Cheat Sheet 3 www.EntityFrameworkTutorial.net
Fluent API – Relationship Configurations Property Mapped DB Mapped Key
One-to-zero-or-one DataType Column DataType column DataType
Int int int, Identity column
modelBuilder.Entity<StudentAddress>() increment by 1
.HasKey(e => e.StudentId); string nvarchar(Max) nvarchar(128)
decimal decimal(18,2) decimal(18,2)
modelBuilder.Entity<Student>()
float real real
.HasOptional(s => s.Address)
.WithRequired(ad => ad.Student) byte[] varbinary(Max) varbinary(128)
datetime datetime datetime
One-to-One bool bit bit
Byte tinyint tinyint
modelBuilder.Entity<StudentAddress>()
short smallint smallint
.HasKey(e => e.StudentId);
long bigint bigint
modelBuilder.Entity<Student>() double float float
.HasRequired(s => s.Address) char No mapping No mapping
.WithRequiredPrincipal(ad => sbyte No mapping No mapping
ad.Student); (throws exception)
object No mapping No mapping
One-to-Many
modelBuilder.Entity<Student>() Database Configurations
.HasRequired<Standard>(s => Set DB Initializer
s.Standard)
Database.SetInitializer<Context>(new
.WithMany(s => s.Students);
DropCreateDatabaseAlways<Context>());

Many-to-Many Database.SetInitializer<Context>(new
DropCreateDatabaseIfModelChanges<Context>());
modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses) Database.SetInitializer<Context>(new
.WithMany(c => c.Students) CreateDatabaseIfNotExists<Context>());
.Map(cs => {
cs.MapLeftKey("StudentRefId"); Remove Plural Table Name Convention
cs.MapRightKey("CourseRefId");
Using
cs.ToTable("StudentCourse");
System.Data.Entity.ModelConfiguration.Conventions;
});
modelBuilder.Conventions
.Remove<PluralizingTableNameConvention>();

Das könnte Ihnen auch gefallen