【问题标题】:EF6 Foreign Key to an existing column in DB数据库中现有列的 EF6 外键
【发布时间】:2014-04-14 08:07:30
【问题描述】:

我有一个 db 架构,并且我使用 EF6 代码先迁移。 我想将 dbo.aspnetuser 中的外键添加到我的数据库中的现有列(使用 MSSQL) 是否可以?怎么办?

将迁移文件更改为此,不起作用: 由于无法确定主键列,因此无法创建表“dbo.AspNetUsers”上具有“consumer_id”列的外键。使用 AddForeignKey fluent API 完全指定外键。

CreateTable(
            "dbo.AspNetUsers",
            c => new
                {
                    Id = c.String(nullable: false, maxLength: 128),
                    UserName = c.String(),
                    PasswordHash = c.String(),
                    SecurityStamp = c.String(),
                    contact_firstname = c.String(),
                    contact_lastname = c.String(),
                    contact_phone = c.String(),
                    contact_phone2 = c.String(),
                    contact_email = c.String(),
                    country = c.String(),
                    state = c.String(),
                    city = c.String(),
                    street = c.String(),
                    postcode = c.String(),
                    longitude = c.Double(),
                    latitude = c.Double(),
                    consumer_id = c.Long(),
                    Discriminator = c.String(nullable: false, maxLength: 128),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.fx_service_consumers", t => t.consumer_id, cascadeDelete: true);

【问题讨论】:

    标签: sql entity-framework ef-code-first


    【解决方案1】:

    您是否使用 fluent api 将对象映射到表?

    我用它来为 Person 对象中的 Address 映射外键:

    this.HasRequired(t => t.PersonAddress ).WithRequiredDependent()
                .Map(m => m.MapKey("IdAddressColumnNameInUserTable"));
    

    和我的对象

    public class Person
    {
         public int id {get;set;}
         public virtual Address PersonAddress {get;set;}
    }
    
    public class Address
    {
        public int id {get;set;}
        public int city {get;set;}
        ...
    }
    

    【讨论】:

    • 嗨,唯一的问题是我的架构中没有其他类,它在数据库中。我已经设法继续没有foreginkey。谢谢
    • @eyalewin 你能发布你的解决方案吗?
    【解决方案2】:

    经过大量阅读和辩论,似乎没有在表“dbo.AspNetUsers”上使用外键的好方法,我设法在没有外键的情况下继续,它对我来说很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多