none
DropCreateDatabaseAlways模式下,在Seed方法中输入中文内容就报错,英文正常 RRS feed

  • 问题

  • 问题如题,代码如下

    public class MusicStoreContextInitializer:DropCreateDatabaseAlways<MusicStoreContext>
        {
            protected override void Seed(MusicStoreContext context)
            {
                context.Artists.Add(new Artist { Name = "Al Di Meola" });
               // context.Artists.Add(new Artist { Name = "周杰伦" });
               // context.Artists.Add(new Artist { Name = "周杰棍" });
    
                context.Genres.Add(new Genre { Name = "Jazz" });
                //context.Genres.Add(new Genre { Name = "流行" });
                
                context.Albums.Add(new Album
                {
                    Artist = new Artist { Name = "Rush" },
                    Genre = new Genre { Name = "Rock" },
                    Price = 9.99m,
                    Title = "Caravan"
                });
                context.Albums.Add(new Album
                {
                    Artist = new Artist { Name = "Song Dongye" },
                    Genre = new Genre { Name = "Folk" },
                    Price = 19.99m,
                    Title = "Anhe Bridge"
                });
    
                base.Seed(context);
            }
        }

    注释掉中文内容之后就正常了,否则在第一次调用数据库内容时会出错。

    是不是LocalDb哪边要设置一下支持中文?

    2016年4月27日 3:51

答案

  • 補充一下:

    純Code First:預設string 會轉成nvarchar

    若是用Code First from Database,根據的你DB設計產生POCO,工具生成會在OnModelCreating方法決定該欄位是否要用nvarhar,IsUnicode=false代表不要用N

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Test>()
            .Property(e => e.Name)
            .IsUnicode(false);
    }


    秘訣無它,唯勤而已 http://www.dotblogs.com.tw/yc421206/

    2016年5月10日 3:18

全部回复

  • 你好 Bill Gu,

    根据你的代码,我做了一个相似的例子, 我这边能正常运行。我的开发工具:vs2015 英文版, localdb, win10英文版,你能不能提供一下详细的错误信息呢?

    public class ProductDatabaseInitializer : DropCreateDatabaseAlways<ProductContext>
        {
            protected override void Seed(ProductContext context)
            {
    
                context.Artists.Add(new Artist() { Name = "周杰伦" });
                context.Artists.Add(new Artist() { Name = "小菲菲" });
    
                GetCategories().ForEach(c => context.Categories.Add(c));
                GetProducts().ForEach(p => context.Products.Add(p));
            }
    
            private static List<Category> GetCategories()
            {
                var categories = new List<Category> {
                    new Category
                    {
                        CategoryID = 1,
                        CategoryName = "Cars"
                    },
                    new Category
                    {
                        CategoryID = 2,
                        CategoryName = "Planes"
                    },
                    new Category
                    {
                        CategoryID = 3,
                        CategoryName = "Trucks"
                    },
                    new Category
                    {
                        CategoryID = 4,
                        CategoryName = "Boats"
                    },
                    new Category
                    {
                        CategoryID = 5,
                        CategoryName = "Rockets"
                    },
                };
    
                return categories;
            }
    
            private static List<Product> GetProducts()
            {
                var products = new List<Product> {
                    new Product
                    {
                        ProductID = 1,
                        ProductName = "Convertible Car",
                        Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
                                      "Power it up and let it go!",
                        ImagePath="carconvert.png",
                        UnitPrice = 22.50,
                        CategoryID = 1
                   },
                    new Product
                    {
                        ProductID = 2,
                        ProductName = "Old-time Car",
                        Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
                        ImagePath="carearly.png",
                        UnitPrice = 15.95,
                         CategoryID = 1
                   },
                    new Product
                    {
                        ProductID = 3,
                        ProductName = "Fast Car",
                        Description = "Yes this car is fast, but it also floats in water.",
                        ImagePath="carfast.png",
                        UnitPrice = 32.99,
                        CategoryID = 1
                    },
                    new Product
                    {
                        ProductID = 4,
                        ProductName = "Super Fast Car",
                        Description = "Use this super fast car to entertain guests. Lights and doors work!",
                        ImagePath="carfaster.png",
                        UnitPrice = 8.95,
                        CategoryID = 1
                    },
                    new Product
                    {
                        ProductID = 5,
                        ProductName = "Old Style Racer",
                        Description = "This old style racer can fly (with user assistance). Gravity controls flight duration." +
                                      "No batteries required.",
                        ImagePath="carracer.png",
                        UnitPrice = 34.95,
                        CategoryID = 1
                    },
                    new Product
                    {
                        ProductID = 6,
                        ProductName = "Ace Plane",
                        Description = "Authentic airplane toy. Features realistic color and details.",
                        ImagePath="planeace.png",
                        UnitPrice = 95.00,
                        CategoryID = 2
                    },
                    new Product
                    {
                        ProductID = 7,
                        ProductName = "Glider",
                        Description = "This fun glider is made from real balsa wood. Some assembly required.",
                        ImagePath="planeglider.png",
                        UnitPrice = 4.95,
                        CategoryID = 2
                    },
                    new Product
                    {
                        ProductID = 8,
                        ProductName = "Paper Plane",
                        Description = "This paper plane is like no other paper plane. Some folding required.",
                        ImagePath="planepaper.png",
                        UnitPrice = 2.95,
                        CategoryID = 2
                    },
                    new Product
                    {
                        ProductID = 9,
                        ProductName = "Propeller Plane",
                        Description = "Rubber band powered plane features two wheels.",
                        ImagePath="planeprop.png",
                        UnitPrice = 32.95,
                        CategoryID = 2
                    },
                    new Product
                    {
                        ProductID = 10,
                        ProductName = "Early Truck",
                        Description = "This toy truck has a real gas powered engine. Requires regular tune ups.",
                        ImagePath="truckearly.png",
                        UnitPrice = 15.00,
                        CategoryID = 3
                    },
                    new Product
                    {
                        ProductID = 11,
                        ProductName = "Fire Truck",
                        Description = "You will have endless fun with this one quarter sized fire truck.",
                        ImagePath="truckfire.png",
                        UnitPrice = 26.00,
                        CategoryID = 3
                    },
                    new Product
                    {
                        ProductID = 12,
                        ProductName = "Big Truck",
                        Description = "This fun toy truck can be used to tow other trucks that are not as big.",
                        ImagePath="truckbig.png",
                        UnitPrice = 29.00,
                        CategoryID = 3
                    },
                    new Product
                    {
                        ProductID = 13,
                        ProductName = "Big Ship",
                        Description = "Is it a boat or a ship. Let this floating vehicle decide by using its " +
                                      "artifically intelligent computer brain!",
                        ImagePath="boatbig.png",
                        UnitPrice = 95.00,
                        CategoryID = 4
                    },
                    new Product
                    {
                        ProductID = 14,
                        ProductName = "Paper Boat",
                        Description = "Floating fun for all! This toy boat can be assembled in seconds. Floats for minutes!" +
                                      "Some folding required.",
                        ImagePath="boatpaper.png",
                        UnitPrice = 4.95,
                        CategoryID = 4
                    },
                    new Product
                    {
                        ProductID = 15,
                        ProductName = "Sail Boat",
                        Description = "Put this fun toy sail boat in the water and let it go!",
                        ImagePath="boatsail.png",
                        UnitPrice = 42.95,
                        CategoryID = 4
                    },
                    new Product
                    {
                        ProductID = 16,
                        ProductName = "Rocket",
                        Description = "This fun rocket will travel up to a height of 200 feet.",
                        ImagePath="rocket.png",
                        UnitPrice = 122.95,
                        CategoryID = 5
                    }
                };
    
                return products;
            }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年4月27日 9:37
  • 需要把错误的异常堆栈贴出来看下原因


    专注于.NET MIS开发框架,C/S架构,SQL Server + ORM(LLBL Gen Pro) + Infragistics WinForms

    2016年4月28日 0:01
  • 只要包含了中文,就在第一次调用数据时抛出异常,也就是在数据库初始化的时候。

    抛出System.Data.DataException异常,Message:初始化数据库时发生异常。有关详细信息,请参阅 InnerException。

    InnerException:对一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。

                        ----EntityValidationErrors:    {System.Data.Entity.Validation.DbEntityValidationResult}

                        ----StackTrace:

       在 System.Data.Entity.Internal.InternalContext.SaveChanges()
       在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
       在 System.Data.Entity.DbContext.SaveChanges()
       在 System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)
       在 System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
       在 System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
    2016年4月28日 8:45
  • 你好 Cole:

    感谢热心解答,异常信息在上一楼。

    2016年4月28日 8:46
  • 你好,

    请查找一下“EntityValidationErrors”属性的值,类似下面这样的图。

    另外,你可以手动在数据中加一条中文信息,看能不能加进去。

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2016年5月4日 8:36
  • 应该不是中文导致错误的,应该是某个应该赋值却没有设置值,你可以把实体的Description字段去除,参考链接:http://www.cnblogs.com/xiaoxiangfeizi/p/3500802.html

    If my post is helpful,please help to vote as helpful, if my post solve your question, please help to make it as answer. My sample

    2016年5月5日 14:30
  • Hi,

    您要用Code First 動態建立Database?還是Code First from Database?

    你把資料表的欄位定義改用nvarchar才能放中文資料到localdb裡面,查詢的時候也要用N,例如 where TestRemark = N'{TEST_REMARK}',EF 會自動幫我們加N

    由於你調用了DropCreateDatabaseAlways,所以最終會動態建立Database,你應該要在localdb動態建立資料,你可以在Property加上[Column(TypeName = "NVARCHAR")]強制欄位使用NVARCHAR

    [Table("test")]
    public partial class Test
    {
        public int Id { get; set; }

        [StringLength(50)]
        [Column(TypeName = "NVARCHAR")]
        public string Name { get; set; }
    }

    localdb 定序

    參考:http://blog.miniasp.com/post/2012/09/03/SQL-Server-2012-Express-LocalDB-Quick-Start.aspx

      • LocalDB 的執行個體定序設定為 SQL_Latin1_General_CP1_CI_AS,無法變更。
      • 但支援資料庫層級資料行層級運算式層級定序。
      • 也就是說,你只要在建立資料庫時指定其定序即可,或是掛載其他資料庫系統移過來的資料庫檔案,或還原自其他資料庫的備份檔也都不會有問題。
      • 自主資料庫遵循自主資料庫定序所定義的中繼資料和 tempdb 定序規則。





    秘訣無它,唯勤而已 http://www.dotblogs.com.tw/yc421206/



    2016年5月9日 7:56
  • 補充一下:

    純Code First:預設string 會轉成nvarchar

    若是用Code First from Database,根據的你DB設計產生POCO,工具生成會在OnModelCreating方法決定該欄位是否要用nvarhar,IsUnicode=false代表不要用N

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Test>()
            .Property(e => e.Name)
            .IsUnicode(false);
    }


    秘訣無它,唯勤而已 http://www.dotblogs.com.tw/yc421206/

    2016年5月10日 3:18