Samran Samran Samran Samran - 2 months ago 23
C# Question

Only one identity column per table is allowed

I have this class :

public class Comment
{
public virtual int Id { get; set; }
public string Body { get; set; }
public DateTime AddDate { get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
public int PostId { get; set; }
public virtual bool IsApproved { get; set; }
public virtual int LikeCount { get; set; }
public int? ParentId { get; set; }
public virtual Comment Parent { get; set; }
public ICollection<Comment> Children { get; set; }
public virtual Member Member { get; set; }
public virtual byte[] RowVersion { get; set; }
}


and I use fluent API like this:

this.HasRequired(x => x.Post)
.WithMany(x => x.Comments)
.WillCascadeOnDelete();

this.HasOptional(x => x.Parent)
.WithMany(x=>x.Children)
.HasForeignKey(x=>x.ParentId)
.WillCascadeOnDelete(false);


When I want to run the project, I get this error:


Multiple identity columns specified for table 'Comments'. Only one
identity column per table is allowed. Visual Studio 2013


I just have one primary key in this class and that is
Id
in first line.

Anyone? I need help

Answer

The problem is that you most probably have more than one key defined. The one that is defined in your model is Id and the other is defined in your fluent API.

I've tried to reproduce your problem and the code worked perfectly.

Here are my models:

public class Comment
{
    public virtual int Id { get; set; }
    public string Body { get; set; }
    public DateTime AddDate { get; set; }
    public virtual Post Post { get; set; }
    public int PostId { get; set; }
    public virtual bool IsApproved { get; set; }
    public virtual int LikeCount { get; set; }
    public int? ParentId { get; set; }
    public virtual Comment Parent { get; set; }
    public ICollection<Comment> Children { get; set; }
    public virtual Member Member { get; set; }
    public virtual byte[] RowVersion { get; set; }
}
public class Post
{
    public int Id { get; set; }
}
public class Member
{
    public int Id { get; set; }
}

And here is the code I've used to check if the models are working properly:

var db = new ApplicationDbContext();
db.Comments.Add(new Comment()
    {
        AddDate = DateTime.Now,
        Body = "asd",
        IsApproved = true,
        LikeCount = 12,
        Member = new Member(),
        Post = new Post()
    });
db.SaveChanges();