2012-10-15 11 views
10

Tôi đang sử dụng EF5 với MVC4. Vấn đề là tôi có dữ liệu lớn trong DB của tôi mà tôi đã nhập từ DB kế thừa. Tôi muốn tải hạt giống dữ liệu đó khi mô hình thay đổi. Câu hỏi của tôi là làm thế nào tôi có thể gieo số lượng lớn dữ liệu đã có trong DB của tôi?EF 5 Mã số đầu tiên di chuyển số lượng lớn SQL dữ liệu Seed

internal sealed class Configuration : MigrationsConfiguration<VoiceLab.Models.EFDataContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = true; 
    } 

    protected override void Seed(VoiceLab.Models.EFDataContext context) 
    { 
    //what to do here to seed thousands or records that are already in db 
    } 

} 

cảm ơn,

Trả lời

17

Đây là cách bạn có thể gieo rắc dữ liệu với số lượng lớn bằng cách chỉ cung cấp các file sql trong phương pháp giống.

public class AppContextInitializer : CreateDatabaseIfNotExists<AppContext> 
{ 
    protected override void Seed(AppContext context) 
    { 
     var sqlFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sql").OrderBy(x => x); 
     foreach (string file in sqlFiles) 
     { 
      context.Database.ExecuteSqlCommand(File.ReadAllText(file)); 
     } 

     base.Seed(context); 
    } 
} 
+0

Tôi nghĩ rằng đây là cách Bilal đang nói về: http://edspencer.me.uk/2012/10/30/seed-data-from-sql -scripts-using-entity-framework-migrations-ef-4-3 / – Rahatur

0

Di chuyển dựa trên mã là phương pháp được khuyến nghị cho cơ sở dữ liệu hiện có (cập nhật cơ sở dữ liệu thủ công) sau khi thay đổi mô hình. Bạn có thể làm điều đó tạo thành PowerShell trong cửa sổ Gói Comand Line. Theo cách đó, dữ liệu hiện có sẽ được bảo toàn.

Nếu bạn là thành viên của nhóm phát triển sử dụng kiểm soát nguồn, bạn nên sử dụng di chuyển hoàn toàn tự động hoặc di chuyển thuần túy dựa trên mã. Do những hạn chế của việc di chuyển tự động bằng cách sử dụng di trú dựa trên mã trong môi trường nhóm được khuyến nghị.

http://msdn.microsoft.com/en-us/data/jj591621

http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

internal sealed class Configuration : MigrationsConfiguration<DataContext> 
{ 
    public Configuration() 
    { 
     AutomaticMigrationsEnabled = false; 

     // if model changes involve data lose 
     AutomaticMigrationDataLossAllowed = true; 

    } 

    protected override void Seed(DataContext context) 
    { 
    //seed only when creating or new database 
    } 

}