Jared Mackey
Jared Mackey

Reputation: 4158

C# Trying to add items into database, getting error

I am trying to add this information into my database. My SQL Server will generate the Id for each row in the table. However, for some reason my code is adding a "0" for Id and I cannot figure out why or where it is coming from and I need to remove it so that the database can just generate it.

Here is my code:

 public class Contact
{
    public Contact()
    {

    }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [Required]
    [StringLength(50)]
    public string Email { get; set; }

    [Column(TypeName = "ntext")]
    [Required]
    public string Message { get; set; }

    [Column(TypeName = "date")]
    [Required]
    public DateTime Date { get; set; }

    [Column(TypeName = "time")]
    [Required]
    public TimeSpan Time { get; set; }
}


public class Context : DbContext
{
    public Context()
        : base("ContactConnectionString")
    {

    }
    public DbSet<Contact> ContactForm { get; set; }
}


public class ImportToDataBase
{


    public static void SubmitToDatabase(string theMessage, string fullName, string emailAddress)
    {




        using (var db = new Context())
        {
            var contact = new Contact()
            {
                Email = emailAddress,
                Message = theMessage,
                Name = fullName,
                Date = DateTime.Now.Date,
                Time = DateTime.Now.TimeOfDay,
                // ID is not set in here
            };
            db.ContactForm.Add(contact);
            db.SaveChanges();
        }


    }
}
}

Upvotes: 0

Views: 135

Answers (2)

Mun
Mun

Reputation: 14308

Try decorating your Id property with the following:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

The Key attribute tells Entity Framework that the Id property is the primary key and should not be included in the insert statement.

Upvotes: 1

codebased
codebased

Reputation: 7073

As a best practice, you need to mark your id with Key and Identity Option.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

For fluent API you can use as:

 HasKey(i => i.ID);
 Property(i => i.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Upvotes: 0

Related Questions