Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

Wondering if i am doing this correctly (Auto-Increment) of BatchID in the database if i manually add a new record it will auto-increment but when i do it via EF the BatchID is zero below is my model class (Batch)

XML
/// <summary>
    /// Represents a Batch.
    /// </summary>
    [Table(Name = "Batch")]
    public class Batch
    {
        /// <summary>
        /// Gets or sets BatchID.
        /// </summary>
        [Key]
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
        public int BatchID { get; set; }

        /// <summary>
        /// Gets or sets Name.
        /// </summary>
        [Column]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the SubBatches
        /// </summary>
        public virtual ICollection<SubBatch> SubBatches { get; set; }
    }


Where i use
SQL
[Key]
        [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
is this the correct way?
Posted
Updated 23-Jul-15 13:07pm
v2

1 solution

You really don't even need all of the attributes you put in there.

EF follows a convention that if there is a property in the class that is either called "Id" or that matches the class name with "Id" appended to it, that property is automatically the primary [Key].

You don't even need all the other stuff unless you're going to make some non-standard key in the database. An auto-incrementing int is the default. If you make something different, then you can start throwing attributes at the code, or skip the attributes and do it through the Fluent configuration.

In your example, all you need is this:
C#
public class Batch
{
    public Batch()
    {
        this.SubBatches = new HashSet<SubBatch>();
    }

    public int BatchID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<SubBatch> SubBatches { get; set; }
}

Oh, and it also helps to initialize the collection...
 
Share this answer
 
v3
Comments
Member 11838038 24-Jul-15 3:16am    
Thanks man, but quick question the way i did it with out Batch() would it be correct?

Just your way is better correct?
Dave Kreskowiak 24-Jul-15 8:03am    
Only if you want to check to see if SubBatches is null every time try to enumerate through the collection.

I don't know about you, but I try ti minimize my use of
if (something == null)
Member 11838038 4-Aug-15 5:25am    
thanks for the help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900