C# .NET 4.0 MVC Inserting a record with primary key

前端 未结 2 1203
再見小時候
再見小時候 2020-12-30 06:19

We have a database with a tables called \'Sites\' This table has the columns, SiteID, Name, Tags, Description, URI, with SiteID being a primary key (It is not set as an Iden

相关标签:
2条回答
  • 2020-12-30 06:35

    If you want a NO IDENTITY primary key column, so you set the id manually, you have 2 possible solutions.

    1. Decorate your id propertie with the following Attributes (DatabaseGenerated...).

        public class Sites
        {
            [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
            public int SiteID { get; set; }
            public string Name { get; set; }
            public string Tags { get; set; }
            public string Description { get; set; }
            public string URI { get; set; }
        }
    

    2. Do it using the ModelBuilder in your DbContext.

        public class CMSModels : DbContext
        {
          //public DbSet<ContentTypeModel> ContentType { get; set; }
          //public DbSet<LayoutModel> Layout { get; set; }
          //public DbSet<PageModel> Page { get; set; }
          //public DbSet<PageZoneModel> PageZone { get; set; }
          public DbSet<Sites> Site { get; set; }
          //public DbSet<ZoneContentModel> ZoneContent { get; set; }
          //public DbSet<ZoneTypeModel> ZoneType { get; set; }
    
          protected override void OnModelCreating(ModelBuilder modelBuilder)
          {
              base.OnModelCreating(modelBuilder);
              modelBuilder.Entity<Sites>().Property(r => r.SiteID) 
                           .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
          }
        }
    
    0 讨论(0)
  • 2020-12-30 07:00

    I think you can understand your problem and solve it reading this article: http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

    0 讨论(0)
提交回复
热议问题