加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在Entity Framework中为引用对象指定列的名称

发布时间:2020-12-15 08:29:33 所属栏目:百科 来源:网络整理
导读:我有一个预定义的数据库,我想使用Entity Framework 4 CodeFirst映射. public class Site{ public int SiteId { get; set; } public string SiteName { get; set; } public DateTime InstallDate { get; set; } public string Phase { get; set; } public str
我有一个预定义的数据库,我想使用Entity Framework 4 CodeFirst映射.
public class Site
{
    public int SiteId { get; set; }
    public string SiteName { get; set; }
    public DateTime InstallDate { get; set; }
    public string Phase { get; set; }
    public string Address { get; set; }
    public string GpsPosition { get; set; }
    public string NetworkDetail { get; set; }
    public string SiteCode { get; set; }
    public string UserGroupCode { get; set; }
    public string InfrastructureNumber { get; set; }
    public string Province { get; set; }

    public virtual ICollection<LcuSetting> LcuSettings { get; set; }
}

另一堂课

public class LcuSetting
{
    public int LCUSettingId { get; set; }
    [Column(Name="Site_Id")]
    public Site Site { get; set; }


    public string Name { get; set; }
    public string IPAddress { get; set; }
    public string SubnetMask { get; set; }
    public string DefaultGateway { get; set; }
}

由于EF4的映射约定,它在表LCUSettings中查找列SiteSiteId,由于Column实际上名为Site_ID,因此无法找到它

在我的DbContext派生类中,我重写OnModelCreating方法并设置要使用的表名.

modelBuilder.Entity<Site>().ToTable("Site");

这很好用.

但是,当我尝试指定列名时,如下所示

modelBuilder.Entity<LcuSetting>().Property(c => c.Site).HasColumnName("Site_Id");

我收到以下异常消息

The type ‘LcuSystemOnline.Models.Site’ must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method ‘System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.Property(System.Linq.Expressions.Expression>)’

我理解异常,但是如何让modelBuilder为站点分配特定的ColumnName

解决方法

在CTP5中,您不能使用Column属性指定我们创建的外键名称.您必须使用流畅的API以这种方式执行此操作:
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Category { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>()
            .HasRequired(p => p.Category)
            .WithMany(c => c.Products)
            .IsIndependent()
            .Map(mc => mc.MapKey(c => c.Id,"CategoryId")); 
    }
}

请注意OnModelCreating方法中对“Map”的调用.这是许多人遇到的问题,我喜欢使用ColumnAttribute来帮助命名.

你可以看到我写的这篇博客文章了解更多细节:
http://blogs.msdn.com/b/adonet/archive/2010/12/10/code-first-mapping-changes-in-ctp5.aspx

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读