Data Annotations are attributes that you apply directly to the
class or properties that you want to affect. These can be found in the System.Component
Model.DataAnnotations namespace.
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
when it’s time to SaveChanges, Entity Framework will check to be sure that the property you have
flagged as Required is not empty. If it is empty, Entity Framework will throw an
exception.
class AnimalType
{
public int Id { get; set; }
[Required]
public string TypeName { get; set; }
}
The data that you refer to as AnimalType in your application might be stored in a table called Spe
cies. The Table annotation allows you to specify this mapping.
上面的配置等价于如下的Fluent API:
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; }
protected override void OnModelCreating
(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<AnimalType>()
.ToTable("Species");
modelBuilder.Entity<AnimalType>()
.Property(p => p.TypeName).IsRequired();
}
}
Organizing Fluent Configurations
You can group configuration by entity type within
individual EntityTypeConfiguration classes, and then tell the DbModelBuilder about
them in the OnModelCreating method. DbModelBuilder has a Configurations property to
which you can add these EntityTypeConfigurations.
using Model;
public class DestinationConfiguration : EntityTypeConfiguration<Destination>
{
public DestinationConfiguration()
{
Property(d => d.Name).IsRequired();
Property(d => d.Description).HasMaxLength(500);
Property(d => d.Photo).HasColumnType("image");
}
}
public class LodgingConfiguration : EntityTypeConfiguration<Lodging>
{
public LodgingConfiguration()
{
Property(l => l.Name).IsRequired().HasMaxLength(200);
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DestinationConfiguration());
modelBuilder.Configurations.Add(new LodgingConfiguration());
}
关于主键
{
[Key]
public int SocialSecurityNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
如果用下面的代码去进行插入,会报错
{
var person = new Person
{
FirstName = "Rowan",
LastName = "Miller",
SocialSecurityNumber = 12345678
};
using (var context = new BreakAwayContext())
{
context.People.Add(person);
context.SaveChanges();
}
}
以为, key属性默认是自增的字段
必须用如下代码来进行修复
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int SocialSecurityNumber { get; set; }
Configuring Database-Generated Options with the Fluent API
.HasKey(t => t.Identifier)
.Property(t => t.Identifier)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);