在EF Code First DatabaseIntializer中重用GUID

所以我试图使用EF构建自定义成员资格。 我真的不知道我在做什么,但到目前为止已经相当顺利了。

我在数据库初始化程序步骤,我试图在项目运行时尽快将数据转储到数据库中。 我的类Application.cs使用GUID作为主键,如下所示。 我试图找出如何将GUID添加到数据库中。

我不知道这是否可能,但这正是我想要做的。 我使用了在VS 2012中创建普通Web应用程序项目并尝试使用EF Code First(实践)重新创建该数据库时获得的默认登录数据库。 这是我到目前为止所得到的。

 public class Applications { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid ApplicationId { get; set; } [StringLength(125)] public string ApplicationName { get; set; } } 

在构建时将数据转储到数据库中的初始化程序(不包括种子)。

  private static List addApplications() { var apps = new List { new Applications { ApplicationId = Guid.NewGuid(), ApplicationName = "Test Login" } }; return apps; } private static List addMemberships() { var mem = new List { new Memberships { UserId = Guid.NewGuid(), ApplicationId = ?, // How can this guid Match the one in // in ApplicationId for the Application Table? } }; return mem; } 

我得到“无效的初始化程序成员声明符”。 我面临的问题是我需要GUID在多个表中对于ApplicationId是相同的。 我甚至都不知道这是可能的还是对的?

我有一种感觉,我必须以某种方式分享它

  Guid AppId; AppId = Guid.NewGuid(); 

在您的Membership模型中,不是存储GUID“ApplicationId”来尝试和引用应用程序,您应该使用类似的导航属性( 有关导航属性的更好描述,请参阅此链接 ):

 public class Memberships { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid UserId { get; set; } //if you set your model up like this entity framework will take care of creating /the foreign key for you. public Application MemberApplication { get; set; } } 

然后只需将适当的应用程序传递给您的方法,如下所示:

 private static List addMemberships(Application app) { var mem = new List { new Memberships { UserId = Guid.NewGuid(), Application = app, } }; return mem; } 

像这样设置模型可以充分利用oop和关系数据库。 希望有所帮助。