I was able to accomplish it by telling Entity Framework that the Id is a Database Generated value. I mapped the Insert procedure to InsertPerson in the PersonMap class and use that when the model is created in the OnModelCreating method. In the stored procedure I generate a new Id and pass this back to Entity Framework. Hope this helps!
PersonMap.cs
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Tell Entity Framework the database will generate the key.
this.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// Properties
this.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(255);
//Map to Stored Procedure
this.MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertPerson")));
}
}
OnModelCreating
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PersonMap());
}
InsertPerson Stored Procedure
CREATE PROCEDURE InsertPerson
-- Since Id is marked as Database Generated we only need
-- a parameter for First Name
@FirstName nvarchar(255) = 0
AS
-- Variable to hold new Id
DECLARE @Id uniqueidentifier
-- Generate a new Id using NEWID function that returns a unique identifier
SET @Id = NEWID()
-- Perform Insert
INSERT INTO [dbo].[Person] VALUES (@Id, @FirstName)
-- Return the Id to Entity Framework
SELECT @Id AS 'Id'