已答复 EF4 Code First CTP5: Seed method no longer works

  • 2010年12月10日 23:53
     
     

    I asked this question on StackOverflow also(http://stackoverflow.com/questions/4414148/ef4-code-first-ctp5-seed-method-no-longer-works)

     

    I had EF Code First CTP4 working fine, and I installed CTP5 today. Now, I get an exception when my database is repopulated.

     

    Here is my model:

     

    public class Member

    {

        public Member()

        {

            DateCreated = DateTime.Now;

            DateUpdated = DateTime.Now;

            DateLastLogin = DateTime.Now;

        }

        [Key, DatabaseGenerated(DatabaseGenerationOption.Identity)]  \\I have tried removing these annotations and the result is the same

        public int MemberId { get; set; }

        [Required,RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]

        public string Email { get; set; }

        [Required,StringLength(20,MinimumLength=2)]

        public string FirstName { get; set; }

        [Required, StringLength(20, MinimumLength = 2)]

        public string LastName { get; set; }

        [Required, StringLength(36, MinimumLength = 2)]

        public string City { get; set; }

        [Required, StringLength(20, MinimumLength = 2)]

        public string State { get; set; }

        [Required, StringLength(20, MinimumLength = 2)]

        public string Zip { get; set; }

        public double GeoLat { get; set; }

        public double GeoLong { get; set; }

        public string AccountStatus { get; set; }

        public DateTime DateCreated { get; private set; }

        public DateTime DateUpdated { get; set; }

        public DateTime DateLastLogin { get; set; }

     

        public virtual PublicProfile Profile { get; set; }        

    }

    Here is the code that is being called in Global.asax.cs

     

    protected void Application_Start()

    {           

         RegisterRoutes(RouteTable.Routes);

         DbDatabase.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlClient");

         DbDatabase.SetInitializer<MeetPplDB>(new Initializer());

    }

     

    public class Initializer : DropCreateDatabaseAlways<MeetPplDB>

    {

        protected override void Seed(MeetPplDB context)

        {

            var Members = new List<Member>

            {

                new Member {

                    Email = "dave@dave.com",

                    City = "San Francisco",

                    AccountStatus = "Active",

                    State = "CA",

                    FirstName = "David",

                    LastName = "Daverson",

                    Zip = "94118",

                    GeoLat = 37.735,

                    GeoLong = -122.392 },

     

                new Member { 

                    Email = "bob@bob.com", 

                    City = "Oakland", 

                    AccountStatus = "Active", 

                    State = "CA", 

                    FirstName = "Bob", 

                    LastName = "Boberson", 

                    Zip = "94601",

                    GeoLat = 37.781,

                    GeoLong = -122.216 },

     

               new Member {

                   Email = "jenny@jenny.com",

                   City = "San Francisco",

                   AccountStatus = "Active",

                   State = "CA",

                   FirstName = "Jenny",

                   LastName = "Jennerson",

                   Zip = "94123",

                   GeoLat = 37.735,

                   GeoLong = -122.392 }

            };

            Members.ForEach(m => context.Members.Add(m));

            context.SaveChanges();

         }

    }

    When it hits the SaveChanges on the context, I get this exception:

     

    Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

     

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

     

    Exception Details: System.Data.UpdateException: Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

     

    Does anyone have any idea what has changed and why this does not work any more? What needs to change for this to work?

答案

  • 2010年12月16日 1:19
    版主
     
     已答复

    Dave,

     

    Thanks for posting all the code.  It turns out that the problem is in the way the relationship between PublicProfile and Member is being determined.  PublicProfile was being made the principal and Member the dependent.  This is a one-to-one relationship where the FK of the dependent is also its PK.  In this situation the PK is made a non-identity column.  This is correct behavior except that the principal and dependent are being detected the wrong way around resulting in Member having a non-identity key.  We will certainly look into making this work better for RTM. For now you can work around the issue by explicitly mapping the relationship between Member and PublicProfile like so:

     

                modelBuilder.Entity<Member>().HasOptional(m => m.Profile).WithRequired(p => p.Member);

     

    This will make Member the principal and hence it will get an Identity PK.  If you want Profile to be required, then you could map it like this:

     

                modelBuilder.Entity<Member>().HasRequired(m => m.Profile).WithRequiredPrincipal(p => p.Member);

     

    Hope this helps.

     

    Thanks,

    Arthur

全部回复

  • 2010年12月13日 21:27
    版主
     
     

    Ucsbmrf,

     

    This line will cause problems:

     

                DbDatabase.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlClient");

     

    The default value for DbDatabase.DefaultConnectionFactory is an instance of SqlConnectionFactory so there is usually no need to change it if you are using SQL Server.  If you want to use SQL Server Compact, then you need to set an instance of SqlCeConnectionFactory.  On the other hand, if you do mean to set a new SqlConnectionFactory then the string you pass to the constructor should be a connection string (without initial catalogue/database name).

     

    Once I removed the line above I had no problem running your code.  If you continue to have problems after fixing the DefaultConnectionFactory or if you have more questions on how to set the DefaultConnectionFactory please feel free to Reply.

     

    Thanks,

    Arthur

  • 2010年12月14日 1:17
     
     

    Hi Arthur,

    Unfortunately, that did not solve the problem.  Application_Start() now reads as:

     

    protected void Application_Start()

    {

    RegisterRoutes(RouteTable.Routes);

            DbDatabase.SetInitializer<MeetPplDB>(new MeetPplDBInitializer());

    }

    I still get the same exception at the same place (full stack trace below)

     

    System.Data.Entity.Infrastructure.DbUpdateException was unhandled by user code

      Message=Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

      Source=EntityFramework

      StackTrace:

           at System.Data.Entity.DbContext.SaveChanges()

           at MeetPpl.MeetPplDBInitializer.Seed(MeetPplDB context) in C:\Dropbox\My Dropbox\Code\MeetPpl\MeetPpl\MeetPpl\Global.asax.cs:line 110

           at System.Data.Entity.Database.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)

           at System.Data.Entity.Database.DbDatabase.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)

           at System.Data.Entity.Database.DbDatabase.<>c__DisplayClass8.<Initialize>b__5()

           at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)

      InnerException: System.Data.UpdateException

           Message=Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

           Source=System.Data.Entity

           StackTrace:

                at System.Data.Mapping.Update.Internal.TableChangeProcessor.DiagnoseKeyCollision(UpdateCompiler compiler, PropagatorResult change, CompositeKey key, PropagatorResult other)

                at System.Data.Mapping.Update.Internal.TableChangeProcessor.ProcessKeys(UpdateCompiler compiler, List`1 changes, Set`1 keys)

                at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler)

                at System.Data.Mapping.Update.Internal.UpdateTranslator.<ProduceDynamicCommands>d__0.MoveNext()

                at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()

                at System.Data.Mapping.Update.Internal.UpdateCommandOrderer..ctor(IEnumerable`1 commands, UpdateTranslator translator)

                at System.Data.Mapping.Update.Internal.UpdateTranslator.ProduceCommands()

                at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)

                at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)

                at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)

                at System.Data.Entity.DbContext.SaveChanges()

           InnerException: 


  • 2010年12月14日 20:25
    版主
     
     

    Ucsbmrf,

     

    I am able to run your code against CTP5 without seeing any errors.  I did need to remove this line: “public virtual PublicProfile Profile { get; set; }” since you don’t include any definition for PublicProfile in the code you posted. 

     

    Could you move the code to a console application and see if you can repro the error using just the code you posted?  If not there is likely something else going on here which is impacting the results you are seeing.  If you can repro it in a console app then hopefully I’ll be able to run your repro and investigate further.

     

    Thanks,

    Arthur

  • 2010年12月15日 17:04
     
     

    Hi Arthur,

    I am still getting the same error.  Here is my code:

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Data.Entity;

    using System.Data.Entity.Database;

    using System.ComponentModel.DataAnnotations;

    using System.Data.Entity.Validation;

     

    namespace EFCTP5_Console

    {

        class Program

        {

            static void Main(string[] args)

            {

                DbDatabase.SetInitializer<EFCTPDB>(new DropCreateDatabaseAlways<EFCTPDB>());

     

                using (var context = new EFCTPDB())

                {

                    var Members = new List<Member>

                    {

                        new Member {

                            Email = "murphdaddy@gmail.com",

                            City = "San Francisco",

                            AccountStatus = "Active",

                            State = "CA",

                            FirstName = "David",

                            LastName = "Murphy",

                            Zip = "94118",

                            GeoLat = 37.735,

                            GeoLong = -122.392 },

     

                        new Member { 

                            Email = "bob@bob.com", 

                            City = "Oakland", 

                            AccountStatus = "Active", 

                            State = "CA", 

                            FirstName = "Bob", 

                            LastName = "Boberson", 

                            Zip = "94601",

                            GeoLat = 37.781,

                            GeoLong = -122.216 },

     

                       new Member {

                           Email = "jenny@jenny.com",

                           City = "San Francisco",

                           AccountStatus = "Active",

                           State = "CA",

                           FirstName = "Jenny",

                           LastName = "Jennerson",

                           Zip = "94123",

                           GeoLat = 37.735,

                           GeoLong = -122.392 }

                    };

     

                    Members.ForEach(m => context.Members.Add(m));

                    try

                    {

                        context.SaveChanges();

                    }

                    catch (DbEntityValidationException ex)

                    {

                        foreach (var failure in ex.EntityValidationErrors)

                        {

                            Console.WriteLine(

                                "{0} failed validation",

                                failure.Entry.Entity.GetType());

     

                            foreach (var error in failure.ValidationErrors)

                            {

                                Console.WriteLine(

                                    "- {0} : {1}",

                                    error.PropertyName,

                                    error.ErrorMessage);

                            }

                        }

                    }

                    catch (Exception e)

                    {

                        Console.WriteLine(

                                    "{0} : {1}\nInner Exception: {2}",

                                    e.Source, e.Message, e.InnerException);

                    }

                    Members = context.Members.ToList();

     

                    var UserPics = new List<MemberPic>

                    {

                        new MemberPic { Url = "/Content/images/blank_boy.png", Member = Members[0] },

                        new MemberPic { Url = "/Content/images/blank_boy.png", Member = Members[1] },

                        new MemberPic { Url = "/Content/images/blank_boy.png", Member = Members[2] },

                        new MemberPic { Url = "/Content/images/google.gif", Member = Members[0] },

                        new MemberPic { Url = "/Content/images/openid.gif", Member = Members[0] },

                        new MemberPic { Url = "/Content/images/verisign.gif", Member = Members[0] }

                    };

                    UserPics.ForEach(p => context.MemberPics.Add(p));

                    try

                    {

                        context.SaveChanges();

                    }

                    catch (DbEntityValidationException ex)

                    {

                        foreach (var failure in ex.EntityValidationErrors)

                        {

                            Console.WriteLine(

                                "{0} failed validation",

                                failure.Entry.Entity.GetType());

     

                            foreach (var error in failure.ValidationErrors)

                            {

                                Console.WriteLine(

                                    "- {0} : {1}",

                                    error.PropertyName,

                                    error.ErrorMessage);

                            }

                        }

                    }

                    catch (Exception e)

                    {

                        Console.WriteLine(

                                    "{0} : {1}\nInner Exception: {2}",

                                    e.Source, e.Message, e.InnerException);

                    }

     

                    UserPics = context.MemberPics.ToList();

     

                    var Profiles = new List<PublicProfile>

                    {

                        new PublicProfile {

                            Member = Members[0],

                            Name = "Dave",

                            Pic = UserPics[0]

                        },

                        new PublicProfile {

                            Member = Members[1],

                            Name = "Bob",

                            Pic = UserPics[1]

                        },

                        new PublicProfile {

                            Member = Members[2],

                            Name = "Jenny",

                            Pic = UserPics[2]

                        }

                    };

     

                    Profiles.ForEach(p => context.PublicProfiles.Add(p));

                    try

                    {

                        context.SaveChanges();

                    }

                    catch (DbEntityValidationException ex)

                    {

                        foreach (var failure in ex.EntityValidationErrors)

                        {

                            Console.WriteLine(

                                "{0} failed validation",

                                failure.Entry.Entity.GetType());

     

                            foreach (var error in failure.ValidationErrors)

                            {

                                Console.WriteLine(

                                    "- {0} : {1}",

                                    error.PropertyName,

                                    error.ErrorMessage);

                            }

                        }

                    }

                    catch (Exception e)

                    {

                        Console.WriteLine(

                                    "{0} : {1}\nInner Exception: {2}",

                                    e.Source, e.Message, e.InnerException);

                    }

                    Profiles = context.PublicProfiles.ToList();

     

                    var Messages = new List<Message>

                    {

                        new Message(Members[0], Members[1]){                    

                            Subject = "yo",

                            Body = "yar",

                            Timestamp = DateTime.Now.Subtract(TimeSpan.FromDays(7))

                        },

                        new Message(Members[1], Members[2]) {                    

                            Subject = "hi",

                            Body = " hi hi" },

                        new Message(Members[2], Members[0]) {                    

                            Subject = "blah",

                            Body = "bah bah" }

                    };

                    Messages.ForEach(m => context.Messages.Add(m));

                    try

                    {

                        context.SaveChanges();

                    }

                    catch (DbEntityValidationException ex)

                    {

                        foreach (var failure in ex.EntityValidationErrors)

                        {

                            Console.WriteLine(

                                "{0} failed validation",

                                failure.Entry.Entity.GetType());

     

                            foreach (var error in failure.ValidationErrors)

                            {

                                Console.WriteLine(

                                    "- {0} : {1}",

                                    error.PropertyName,

                                    error.ErrorMessage);

                            }

                        }

                    }

                    catch (Exception e)

                    {

                        Console.WriteLine(

                                    "{0} : {1}\nInner Exception: {2}",

                                    e.Source, e.Message, e.InnerException);

                    }

                    Messages = context.Messages.ToList();

     

                    var Messages2 = new List<Message>

                    {

                        new Message(Members[1], Members[0], Messages[0].ThreadId) {

                            Subject = "yo",

                            Body = "yar",

                            Timestamp = DateTime.Now.Subtract(TimeSpan.FromDays(5))

                        },

                        new Message(Members[2], Members[1], Messages[1].ThreadId) {

                            Subject = "hi",

                            Body = " hi hi" },

                        new Message(Members[0], Members[2], Messages[2].ThreadId) {

                            Subject = "blah",

                            Body = "bah bah" }

                    };

                    Messages2.ForEach(m => context.Messages.Add(m));                

     

                    try

                    {

                        context.SaveChanges();

                    }

                    catch (DbEntityValidationException ex)

                    {

                        foreach (var failure in ex.EntityValidationErrors)

                        {

                            Console.WriteLine(

                                "{0} failed validation",

                                failure.Entry.Entity.GetType());

     

                            foreach (var error in failure.ValidationErrors)

                            {

                                Console.WriteLine(

                                    "- {0} : {1}",

                                    error.PropertyName,

                                    error.ErrorMessage);

                            }

                        }

                    }

                    catch (Exception e)

                    {

                        Console.WriteLine(

                                    "{0} : {1}\nInner Exception: {2}",

                                    e.Source, e.Message, e.InnerException);

                    }

     

                    Console.WriteLine("Press any key to exit.");

                    Console.ReadKey();

                }        

            }

        }

        //Context

        public class EFCTPDB : DbContext

        {

            public DbSet<Member> Members { get; set; }

            public DbSet<AuthenticationToken> AuthenticationTokens { get; set; }

            public DbSet<TempAuthenticationToken> TempAuthenticationTokens { get; set; }

            public DbSet<PublicProfile> PublicProfiles { get; set; }

            public DbSet<BlockedMember> BlockedUsers { get; set; }

            public DbSet<PendingMember> PendingUsers { get; set; }

            public DbSet<Message> Messages { get; set; }

            public DbSet<ProfileView> ProfileViews { get; set; }

            public DbSet<MemberPic> MemberPics { get; set; }

            public DbSet<PicFlag> FlaggedPics { get; set; }

            public DbSet<TempPic> TempPics { get; set; }

     

            protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)

            {

                base.OnModelCreating(modelBuilder);

     

                modelBuilder.Entity<AuthenticationToken>().HasKey(p => new { p.OpenIdClaimedIdentifier });

            }

        }   

        //Model

        public class Member

        {

            public Member()

            {

                DateCreated = DateTime.Now;

                DateUpdated = DateTime.Now;

                DateLastLogin = DateTime.Now;

            }

            public int MemberId { get; set; }

            [Required, RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address")]

            public string Email { get; set; }

            [Required, StringLength(20, MinimumLength = 2)]

            public string FirstName { get; set; }

            [Required, StringLength(20, MinimumLength = 2)]

            public string LastName { get; set; }

            [Required, StringLength(36, MinimumLength = 2)]

            public string City { get; set; }

            [Required, StringLength(20, MinimumLength = 2)]

            public string State { get; set; }

            [Required, StringLength(20, MinimumLength = 2)]

            public string Zip { get; set; }

            public double GeoLat { get; set; }

            public double GeoLong { get; set; }

            public string AccountStatus { get; set; }

            public DateTime DateCreated { get; private set; }

            public DateTime DateUpdated { get; set; }

            public DateTime DateLastLogin { get; set; }

            //public string deleteme { get; set; }

     

            public virtual PublicProfile Profile { get; set; }

     

            public virtual ICollection<AuthenticationToken> AuthenticationTokens { get; set; }

            public virtual ICollection<BlockedMember> BlockedMembers { get; set; }

            public virtual ICollection<Message> Messages { get; set; }

            public virtual ICollection<ProfileView> ProfileViews { get; set; }

            public virtual ICollection<MemberPic> MemberPics { get; set; }

            public virtual ICollection<PicFlag> FlaggedPics { get; set; }

        }

     

        public class AuthenticationToken

        {

            public AuthenticationToken()

            {

                DateCreated = DateTime.Now;

                DateLastUsed = DateTime.Now;

                UsageCount = 0;

            }

            public int AuthenticationTokenId { get; set; }

            [Required]

            public string OpenIdClaimedIdentifier { get; set; }

            public string OpenIdFriendlyIdentifier { get; set; }

            public DateTime DateCreated { get; private set; }

            public DateTime DateLastUsed { get; set; }

            public int UsageCount { get; set; }

     

            public virtual Member Member { get; set; }

        }

     

        public class TempAuthenticationToken

        {

            public TempAuthenticationToken()

            {

                DateCreated = DateTime.Now;

                Expires = DateTime.Now.AddDays(1);

            }

            [Key]

            public int TempAuthenticationTokenId { get; set; }

            public string Email { get; set; }

            public string OpenIdClaimedIdentifier { get; set; }

            public string OpenIdFriendlyIdentifier { get; set; }

            public DateTime DateCreated { get; private set; }

            public DateTime Expires { get; private set; }

        }

     

        public class BlockedMember

        {

            public BlockedMember()

            {

                DateCreated = DateTime.Now;

            }

     

            [Key]

            public int BlockedId { get; set; }

            public DateTime DateCreated { get; private set; }

     

            public virtual Member Member { get; set; }

            public virtual Member Blocked { get; set; }

        }

     

        public class PendingMember

        {

            public int PendingMemberId { get; set; }

            public int MemberId { get; set; }

            public string PendingKeyString { get; set; }

            public DateTime Expiration { get; set; }

        }

     

        public class PublicProfile

        {

            public PublicProfile()

            {

                DateCreated = DateTime.Now;

                DateUpdated = DateTime.Now;

            }

            public int id { get; set; }

            public bool Searchable { get; set; }

            public string Name { get; set; }

            public string City { get; set; }

            public string State { get; set; }

            public string Gender { get; set; }

            public string SexualPreference { get; set; }

            public string Ethnicity { get; set; }

            public int Height { get; set; }

            public string AboutMe { get; set; }

            public string Profession { get; set; }

            public string HobbiesInterests { get; set; }

            public string AboutYou { get; set; }

            public DateTime DateCreated { get; private set; }

            public DateTime DateUpdated { get; set; }

     

            public virtual MemberPic Pic { get; set; }

            public virtual Member Member { get; set; }

            public virtual ICollection<ProfileView> ProfileViews { get; set; }

        }

     

        public class ProfileView

        {

            public ProfileView()

            {

                Timestamp = DateTime.Now;

            }

            public Int64 id { get; set; }

            public DateTime Timestamp { get; private set; }

            public virtual Member Viewer { get; set; }

            public virtual PublicProfile ProfileViewed { get; set; }

        }

     

        public class Message

        {

            public Message() { }

            public Message(Member from, Member to)

            {

                this.Sender = from;

                this.Receiver = to;

                this.Timestamp = DateTime.Now;

                this.Read = false;

                this.Archived = false;

                this.To = to.Profile.Name;

                this.From = from.Profile.Name;

                this.FromEmail = from.Email;

                this.ThreadId = Guid.NewGuid();

            }

            public Message(Member from, Member to, Guid threadId)

            {

                this.Receiver = to;

                this.Sender = from;

                this.Timestamp = DateTime.Now;

                this.Read = false;

                this.Archived = false;

                this.To = to.Profile.Name;

                this.From = from.Profile.Name;

                this.FromEmail = from.Email;

                this.ThreadId = threadId;

            }

            public int MessageId { get; set; }

            public Guid ThreadId { get; private set; }

            public bool Read { get; set; }

            public bool Archived { get; set; }

            public string Subject { get; set; }

            public string Body { get; set; }

            public string To { get; private set; }

            public string From { get; private set; }

            public string FromEmail { get; private set; }

            public DateTime Timestamp { get; set; }

     

            public virtual Member Sender { get; set; }

            public virtual Member Receiver { get; set; }

        }

     

        public class ThreadListing

        {

            public string From;

            public string Subject;

            public DateTime Timestamp;

            public string Id;

            public bool Read;

        }

     

        public class JsonMessage

        {

            public string From;

            public string Timestamp;

            public string Subject;

            public string Body;

            public string ImageURL;

        }

     

        public class PublicPic

        {

            public string Url;

            public string Caption;

        }

        public class Pic

        {

            public int id;

            public string Url;

            public string Caption;

            public string DateCreated;

            public int ViewCount;

        }

     

        public class MemberPic

        {

            public MemberPic()

            {

                DateCreated = DateTime.Now;

                DateUpdated = DateTime.Now;

                ViewCount = 0;

            }

            public int id { get; set; }

            public string Url { get; set; }

            public string Caption { get; set; }

            public DateTime DateCreated { get; private set; }

            public DateTime DateUpdated { get; set; }

            public int ViewCount { get; set; }

     

            public virtual Member Member { get; set; }

            public virtual ICollection<PicFlag> Flags { get; set; }

        }

     

        public class PicFlag

        {

            public PicFlag()

            {

                Timestamp = DateTime.Now;

            }

            public int id { get; set; }

            public virtual Member Member { get; set; }

            public virtual MemberPic Pic { get; set; }

            public DateTime Timestamp { get; private set; }

        }

     

        public class TempPic

        {

            public TempPic()

            {

                Timestamp = DateTime.Now;

            }

            public int id { get; set; }

            public string Url { get; set; }

            public DateTime Timestamp { get; private set; }

     

            public virtual Member Member { get; set; }

        }    

    }

    /****App.config*****/
    <configuration>
        <connectionStrings>
            <add name="EFCTPDB" connectionString="Server=(local);Database=EFCTPDB;Integrated Security=true" providerName="System.Data.SqlClient" />        
        </connectionStrings>
    </configuration>

    Any ideas?

    Thanks,
    Dave (ucsbmrf)

  • 2010年12月16日 1:19
    版主
     
     已答复

    Dave,

     

    Thanks for posting all the code.  It turns out that the problem is in the way the relationship between PublicProfile and Member is being determined.  PublicProfile was being made the principal and Member the dependent.  This is a one-to-one relationship where the FK of the dependent is also its PK.  In this situation the PK is made a non-identity column.  This is correct behavior except that the principal and dependent are being detected the wrong way around resulting in Member having a non-identity key.  We will certainly look into making this work better for RTM. For now you can work around the issue by explicitly mapping the relationship between Member and PublicProfile like so:

     

                modelBuilder.Entity<Member>().HasOptional(m => m.Profile).WithRequired(p => p.Member);

     

    This will make Member the principal and hence it will get an Identity PK.  If you want Profile to be required, then you could map it like this:

     

                modelBuilder.Entity<Member>().HasRequired(m => m.Profile).WithRequiredPrincipal(p => p.Member);

     

    Hope this helps.

     

    Thanks,

    Arthur