Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have been going through the early stages of a tutorial on youtube http://www.youtube.com/watch?v=WwmUFTWEh6Y

public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
{
    if (!IsAdmin)
    {
        return RedirectToAction("Index");
    }

    Post post = GetPost(id);
    post.Title = title;
    post.Body = body;
    post.DateTime = dateTime;
    post.Tags.Clear();

    tags = tags ?? string.Empty;
    string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string tagName in tagNames)
    {
        post.Tags.Add(GetTag(tagName));
    }

    if (!id.HasValue)
    {
        model.AddToPosts(post);
    }
    model.SaveChanges();
    return RedirectToAction("Details", new { id = post.ID });
}

public ActionResult Edit(int? id)
{
    Post post = GetPost(id);
    StringBuilder tagList = new StringBuilder();
    foreach (Tag tag in post.Tags)
    {
        tagList.AppendFormat("{0} ", tag.Name);
    }
    ViewBag.Tags = tagList.ToString();
    return View(post);
}


private Tag GetTag(string tagName)
{
    return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() { Name = tagName };
}

private Post GetPost(int? id)
{
    return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : new Post() { ID = -1 };
}

I am getting an aspx error "Cannot insert explicit value for identity column in table 'Posts' when IDENTITY_INSERT is set to OFF." I know this is because it is trying to insert an ID of -1 when the database updates and I dont want that. Should it just create a new ID if im passing in -1? Thats whats happens in the tutorial. I dont know why mine is acting differently.

=========================================================== EDIT The database was created using the database designer not through code, I have looked at the code though and cannot see any Autogenerated property or IsDbGenerated attribute, where on earth would I insert this?

 // <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="CollateralSystems.Models", Name="Post")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Post : EntityObject
{
    #region Factory Method

    /// <summary>
    /// Create a new Post object.
    /// </summary>
    /// <param name="id">Initial value of the ID property.</param>
    /// <param name="title">Initial value of the Title property.</param>
    /// <param name="dateTime">Initial value of the DateTime property.</param>
    /// <param name="body">Initial value of the Body property.</param>
    public static Post CreatePost(global::System.Int32 id, global::System.String title, global::System.DateTime dateTime, global::System.String body)
    {
        Post post = new Post();

        post.ID = id;
        post.Title = title;
        post.DateTime = dateTime;
        post.Body = body;
        return post;
    }

    #endregion
    #region Primitive Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    /// 

    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int32 ID
    {
        get
        {
            return _ID;
        }
        set
        {
            if (_ID != value)
            {
                OnIDChanging(value);
                ReportPropertyChanging("ID");
                _ID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("ID");
                OnIDChanged();
            }
        }
    }
    private global::System.Int32 _ID;
    partial void OnIDChanging(global::System.Int32 value);
    partial void OnIDChanged();
share|improve this question
    
What are you using for DB querying? Entity Framework? – Andrei Jul 29 '13 at 21:19
    
It's possible the tutorial is using [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on the ID value. – anaximander Jul 29 '13 at 21:21
    
@anaximander, the other way around is more likely - DB has an auto incrementing column, while EF knows nothing about it and generates code for inserting ID – Andrei Jul 29 '13 at 21:23
    
Exactly - the asker's problem is that they don't have that option set, while the tutorial they're following probably does... – anaximander Jul 30 '13 at 8:16
up vote 0 down vote accepted

Most likely in the database column ID (or similar) in table Posts was created as auto generated column - that is Db is responsible for providing a value for this column whenever new record is being inserted in the table. As a consequence of this, explicit insert of values for this column is forbidden (not entirely true, it is still possible, but not necessary here).

However the ORM system you are using knows nothing about that specifics of the column, so when it receives a command to insert new Posts object into the database, it generates SQL to insert every property that was mapped to a column, including ID. Of course this SQL fails, since insert of ID values it forbidden in the DB.

To resolve this problem, you should set up the ORM properly. If you are using EF or LINQ to SQL - check out the DB context, and in particular properties of Posts.ID. Most likely its AutoGenerated property is set to false, which is not correct. Set it to true and your insert will work as expected.

Alternatively you can go to the generated DataContext class, find class Posts there and make sure its property ID has attribute IsDbGenerated.

share|improve this answer
    
I forgot to "Update model from database" after setting the identity field. So stupid, and I waste your time sorry – JMG Jul 29 '13 at 22:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.