Alex Rivera | Logout

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

Asked 2011-07-19T14:35:58.180
14

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 Identity because we want to add our own ID)

We have been using .NET 4.0 MVC with C# and have setup everything up in the code which we need. We can select things from the database and display them so we know that is working. But when we try to insert we get a Cannot insert the value NULL into column 'SiteID' error.

If I set the column as an Identity so that it auto generates, or if I take off the primary key then it is fine, but as I said it should be a primary key and we want to insert out own ID's.

My code is below (We get the error on SaveChanges() but have checked in the debugger and SiteID is definitely being assigned an int)

Sites

public class Sites
{
    [Key]
    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; }
}

CMSModels

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; }
}

HomeController:

private CMSModels models = new CMSModels();

public ActionResult Index()
{
    Sites site = new Sites { SiteID = 4, Name = "Name", Description = "Desc", Tags = "", URI = "" };

    models.Site.Add(site);
    models.SaveChanges();

    return View(models.Site.ToList());
}

                    
                    
                    
Edit
Report

1 Answer

-1

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/

answered 2011-07-19T15:40:35.350

Your Answer