1

EF 4.1 코드를 사용하고 있습니다. 첫 번째 설정은 엔티티입니다. 여기 EF가 내가 설정 한 속성을 대체합니다.

public class Vendor 
{ 
    public int VendorId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<VendorProduct> VendorProducts { get; set; } 
} 
public class VendorProduct 
{ 
    public int VendorProductId { get; set; } 
    public int ProductId { get; set; } 
    public int VendorId { get; set; } 
    public string VendorProductNumber { get; set; } 
    public int Quantity { get; set; } 
    public decimal SalesPrice { get; set; } 
    public Product Product { get; set; } 
    public Vendor Vendor { get; set; } 
} 
public class Product 
{ 
    public int ProductId { get; set; } 
    public string Name { get; set; } 
    public string Manufacturer { get; set; } 
    public string ManufacturerNumber { get; set; } 
    public string UPC { get; set; } 
    public decimal SalesPrice { get; set; } 
    public string Description { get; set; } 
    public virtual ICollection<VendorProduct> VendorProducts { get; set; } 
} 

여기에 DbContext 인 구성

public class VendorConfiguration : EntityTypeConfiguration<Vendor> 
{ 
    public VendorConfiguration() 
    { 
     Property(p => p.Name).IsOptional().HasMaxLength(128); 
    } 
} 
public class ProductConfiguration : EntityTypeConfiguration<Product> 
{ 
    public ProductConfiguration() 
    { 
     //HasKey(p => p.ProductId); 
     //HasMany(p => p.Images).WithOptional(); 
     Property(p => p.Name).IsOptional().HasMaxLength(128); 
     Property(p => p.Manufacturer).IsOptional().HasMaxLength(64); 
     Property(p => p.ManufacturerNumber).IsOptional().HasMaxLength(32); 
     Property(p => p.UPC).IsOptional().HasMaxLength(32); 
     Property(p => p.SalesPrice).IsOptional(); 
    } 
} 
    public VendorProductConfiguration() 
    { 
     //HasKey(v => v.VendorProductId); 
     Property(o => o.Quantity).IsRequired(); 
     Property(o => o.SalesPrice).IsRequired(); 
     Property(o => o.VendorId).IsRequired(); 
     Property(o => o.ProductId).IsRequired(); 
     Property(o => o.VendorProductNumber).IsOptional().HasMaxLength(50); 
     HasRequired(o => o.Product).WithMany(p => p.VendorProducts).HasForeignKey(o => o.ProductId).WillCascadeOnDelete(false); 
    } 

이다.

public class UbidContext : DbContext 
{ 
    public IDbSet<Product> Products { get; set; } 
    public IDbSet<Vendor> Vendors { get; set; } 
    public IDbSet<VendorProduct> VendorProducts { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 

     // Add any configuration or mapping stuff here 
     modelBuilder.Configurations.Add(new VendorConfiguration()); 
     modelBuilder.Configurations.Add(new VendorProductConfiguration()); 
     modelBuilder.Configurations.Add(new ProductConfiguration()); 
    } 


    public void Seed(UbidContext context) 
    { 
     //Create our indexes 
     context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_Name ON Products (Name)"); 
     context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_Manufacturer ON Products (Manufacturer)"); 
     context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_ManufacturerNumber ON Products (ManufacturerNumber)"); 
     context.Database.ExecuteSqlCommand("CREATE INDEX IX_Products_UPC ON Products (UPC)"); 

     //Add vendors to the database 
     AddVendors(context); 
     context.SaveChanges(); 

     //Add products to the database 
     AddProducts(context); 
     context.SaveChanges(); 

     //Add vendor products to the database 
     AddVendorProducts(context); 
    } 

    private static void AddVendors(UbidContext context) 
    { 
     new List<Vendor> 
      { 
       new Vendor() 
        { 
         Name = "TestVendor1", 
        }, 
       new Vendor() 
        { 
         Name = "TestVendor2", 
        }, 
       new Vendor() 
        { 
         Name = "TestVendor3", 
        } 
      }.ForEach(v => context.Vendors.Add(v)); 
    } 

    private static void AddProducts(UbidContext context) 
    { 
     Image[] images = new Image[1]; 
     images[0] = new Image 
     { 
      Url = "http://content.etilize.com/Thumbnail/10006997.jpg" 
     }; 

     new List<Product> 
      { 
       new Product() 
        { 
         Manufacturer = "StarTech.com", 
         ManufacturerNumber = "SV211K", 
         Name = "StarTech.com SV211K KVM Switch - 2 x 1 - 2 x HD-15 Video", 
         UPC = "SV211K", 
         Images = images 
        }, 
       new Product() 
        { 
         Manufacturer = "Targus Group International", 
         ManufacturerNumber = "CBT300", 
         Name = "Targus BlackTop Standard Notebook Case - Clamshell - Carrying Strap - 5 Pocket - Nylon - Black, Blue", 
         UPC = "CBT300" 
        }, 
       new Product() 
        { 
         Manufacturer = "Lenovo Group Limited", 
         ManufacturerNumber = "31P8700", 
         Name = "Lenovo Optical ScrollPoint Pro Mouse - Optical - USB, PS/2", 
         UPC = "31P8700" 
        }, 
       new Product() 
        { 
         Manufacturer = "Epson Corporation", 
         ManufacturerNumber = "C823071", 
         Name = "Epson Serial Interface Board with 32K Buffer - 1 x RS-232 Serial", 
         UPC = "C823071" 
        }, 
       new Product() 
        { 
         Manufacturer = "Cisco Systems, Inc", 
         ManufacturerNumber = "WSX4013", 
         Name = "Cisco Catalyst 4000 Series Supervisor Engine II-Plus - 2 x GBIC, 1 x - Supervisor Engine", 
         UPC = "WSX4013" 
        } 
      }.ForEach(p => context.Products.Add(p)); 
    } 

    private static void AddVendorProducts(UbidContext context) 
    { 
     Random random = new Random(); 

     var vps = new List<VendorProduct>() 
      { 
       new VendorProduct() 
        { 
         ProductId = 1, 
         VendorId = 1, 
         Quantity = random.Next(3, 40), 
         SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)), 
        }, 
       new VendorProduct() 
        { 
         ProductId = 2, 
         VendorId = 1, 
         Quantity = random.Next(3, 40), 
         SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)), 
        }, 
       new VendorProduct() 
        { 
         ProductId = 3, 
         VendorId = 1, 
         Quantity = random.Next(3, 40), 
         SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)), 
        }, 
       new VendorProduct() 
        { 
         ProductId = 4, 
         VendorId = 2, 
         Quantity = random.Next(3, 40), 
         SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)), 
        }, 
       new VendorProduct() 
        { 
         ProductId = 4, 
         VendorId = 3, 
         Quantity = random.Next(3, 40), 
         SalesPrice = Converter.ConvertObjToDecimal(random.Next(20, 400)), 
        } 
      }; 
     foreach (var vp in vps) 
      context.VendorProducts.Add(vp); 
    } 

    public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<UbidContext> 
    { 
     protected override void Seed(UbidContext context) 
     { 
      context.Seed(context); 

      base.Seed(context); 
     } 
    } 

    static UbidContext() 
    { 
     Database.SetInitializer<UbidContext>(new DropCreateIfChangeInitializer()); 
    } 
} 

지금 무슨 일, 패턴을가 VendorProducts에 도달 할 때, 첫 번째가 잘 추가되지만 EF는 공급 업체 객체를 설정하지 않는 것처럼 보이기 때문에 두 번째는 저장되지 않습니다입니다 벤더 및/또는 productid가 동일한 컨텍스트 내의 이전 엔티티에 사용 된 경우 벤더 또는 제품을 채우지 않으므로 null로 설정됩니다. 내 코드에서 볼 수 있듯이 아래 명시 적으로 VendorId를 설정하고 있지만 EF가 데이터를 db로 보낼 때 VendorId는 null입니다. 더 많은 정보가 필요하시면 알려주십시오.

감사

+0

흠, 질문 : 1) "* 첫 번째 항목은 정상적으로 추가되었지만 두 번째 항목은 저장되지 않습니다 *"는 의미는 무엇입니까? 'SaveChanges'는 아무것도 저장되지 않았거나 모든 것이 트랜잭션입니다. 'SaveChanges'에서 예외를 얻었나요 아니면 DB에서 첫 번째 일 뿐이고 다른 것들은 누락 되었습니까? 2) "*하지만 EF가 데이터를 db로 보낼 때 VendorId가 null입니다. *": 'VendorId'는 int이고, null이 될 수 없습니다 - 정확히 무엇을 의미합니까? – Slauma

답변

0

내가 복사 EF 4.1 콘솔 응용 프로그램에 코드를 붙여 넣은. 내가 그것을 실행하면 나는 데이터베이스 (SQL 서버 2008 R2 익스프레스)에서이 결과를 얻을 :

EFSeedTest

난 단지 이미지와 함께 물건을 제거한하고 Converter.ConvertObjToDecimal가 (컴파일되지 않았다, 내가 직접 사용하고

random.Next).

이것은 코드에서 기대하는 것입니다. 다른 결과가 나옵니까?

+0

답장을 보내고 코드를 테스트 해 주셔서 감사합니다. 행 2를 실행할 때 localy를 실행하면 ProductId 2가 표시됩니다. 행 3에 대한 VendorId NULL, ProductId 3 가져 오기 : VendorId NULL, 행 4는 괜찮습니다. 행 5는 ProductId를 가져옵니다. NULL : VendorId 3. – no1ross

+0

시드 함수에서 추가 컨텍스트 SavingChanges를 제거하여 문제를 해결했습니다. – no1ross

+0

@ no1ross : 그러나 데이터베이스에서'ProductId' 또는'VendorId'가'NULL' 인 것은 불가능합니다. 귀하의 질문에 표시된 코드를 사용하여 ** DB에서 ** null을 사용할 수없는 열 **입니다. DB에 실제로'NULL'을 얻는다면 실제로 사용하고있는 코드와 질문에서 제공 한 코드에 중요한 차이가 있다고 생각합니다. – Slauma

관련 문제