日期:2014-05-16 浏览次数:20362 次
EF基础二,EF5,NET4.5,ANNOTATION AND FLUENT API,MOST FOCUS ON ENTITYTYPECONFIGURATION.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace BlueSea { class Program { static void Main(string[] args) { Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlueSeaContext>()); InsertDestination(); InsertTrip(); UpdateTrip(); InsertPserson(); UpdatePerson(); } private static void InsertDestination() { var destination = new Destination { Country = "Indonesia", Description = "Tourism in Bali", Name = "Bali" }; using (var context = new BlueSeaContext()) { context.Destinations.Add(destination); context.SaveChanges(); } } private static void InsertTrip() { var trip = new Trip { CostUSD = 800, StatrtDate = new DateTime(2013, 3, 15), EndDate = new DateTime(2013, 3, 20) }; using (var context = new BlueSeaContext()) { context.Trips.Add(trip); context.SaveChanges(); } } private static void UpdateTrip() { using (var cntext = new BlueSeaContext()) { var trip = cntext.Trips.FirstOrDefault(); trip.CostUSD = 750; cntext.SaveChanges(); } } private static void InsertPserson() { var person = new Person { FirstName = "Martin", LastName = "Jack", SocialSecurityNumber = 12345678 }; using (var context = new BlueSeaContext()) { context.People.Add(person); context.SaveChanges(); } } private static void UpdatePerson() { using (var context = new BlueSeaContext()) { var person = context.People.FirstOrDefault(); person.FirstName = "Peter"; context.SaveChanges(); } } } public class Destination { public int DestinatonID { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public byte[] Photo { get; set; } public virtual ICollection<Lodging> Lodgings { get; set; } } public class DestinationConfiguration : EntityTypeConfiguration<Destination> { public DestinationConfiguration() { HasKey(d => d.DestinatonID); Property(d => d.Name).IsRequired(); Property(d => d.Description).HasMaxLength(500); Property(d => d.Photo).HasColumnType("image"); } } public class Lodging { public int LodgingID { get; set; } public string Name { get; set; } public string Owener { get; set; } public bool IsResort { get; set; } public decimal MileFromAirport { get; set; } public virtual Destination Destination { get; set; } } public class LodgingConfiguration : EntityTypeConfiguration<Lodging> { public LodgingConfiguration() { Property(l => l.Name).IsRequired().HasMaxLength(200); Property(l => l.MileFromAirport).HasPrecision(8, 1); Property(l => l.Owener).IsUnicode(fals