locked
Entity Framework Code First - Stop autoincrement and use my Primary Key RRS feed

  • Question

  • Hi Guys,

    I have created a class:

    Public Class Person
    
    Public Property PersonId() As Integer
    Public Property FirstName() As String
    Public Property LastName() As String
    
    End Class

    I have created the DbContext:

    Imports System.Data.Entity Namespace PeopleModel Public Class PeopleContext Inherits DbContext Public Property People() As DbSet(Of Person) End Class End Namespace

    Everything works fine when i hook it up to the database,

    The person class is given an auto inc number for the Primary key

    BUT i want to allocate my own ID's to people, and i want the ID's i allocate to be saved to the database

    How can i tell EF to use the ID's i have given and stop using auto inc's?

    Monday, May 21, 2012 8:14 PM

Answers

  • Hi Mike;

    Add the following attribute to the Primary Key field to turn off auto generated key values.

    <DatabaseGenerated(DatabaseGeneratedOption.None)> _
    Public Property PersonId() As Integer

    To use annotations, you must add a reference to EntityFramework.dll and System.ComponentModel.DataAnnotations.dll to your project, and you must add a Imports statement for the System.ComponentModel.DataAnnotations namespace to the source file where your model is defined.

      

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, May 21, 2012 8:54 PM

All replies

  • Hi Mike;

    Add the following attribute to the Primary Key field to turn off auto generated key values.

    <DatabaseGenerated(DatabaseGeneratedOption.None)> _
    Public Property PersonId() As Integer

    To use annotations, you must add a reference to EntityFramework.dll and System.ComponentModel.DataAnnotations.dll to your project, and you must add a Imports statement for the System.ComponentModel.DataAnnotations namespace to the source file where your model is defined.

      

    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, May 21, 2012 8:54 PM
  • Worked perfect!

    If there a document to show all the annotations and how they work? - i keepp picking up the odd one here and there!

    Monday, May 21, 2012 9:38 PM
  • Hi Mike;

    Here are some other Data Annotations that can be used.

    Code First Data Annotations

       


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Tuesday, May 22, 2012 1:31 AM
  • Thanks, It was very helpful
    Tuesday, October 9, 2012 6:37 AM
  • [KeyDatabaseGenerated(DatabaseGeneratedOption.None)]
    
    • Proposed as answer by Megan Mc Monday, October 13, 2014 1:36 PM
    Friday, March 28, 2014 8:59 PM