c# - 创建复合关键 Entity Framework

标签 c# entity-framework entity-framework-5 composite-key

不久,我想在保留主键的表上创建复合键,以提高 sql server 搜索性能。每当我搜索没有主键(即一串 GUID)的实体时,200k 数据表就会出现性能问题。假设我有 3 个类

public class Device{

    public int ID { get; set; } 
    public string UDID { get; set; }
    public string ApplicationKey { get; set; }
    public string PlatformKey { get; set; }

    public ICollection<NotificationMessageDevice> DeviceMessages { get; set; } 
}

public class NotificationMessageDevice { 

    [Column(Order = 0), Key, ForeignKey("NotificationMessage")]
    public int NotificationMessage_ID { get; set; }

    [Column(Order = 1), Key, ForeignKey("Device")]
    public int Device_ID { get; set; }

    public virtual Device Device { get; set; }
    public virtual NotificationMessage NotificationMessage { get; set; }
}

public class NotificationMessage { 

    public int ID { get; set; }
    public string Text { get; set; }
    public DateTime CreateDate { get; set; }
}

        modelBuilder.Entity<Device>().HasKey(t => new { t.ID, t.ApplicationKey, t.PlatformKey, t.UDID });

问题是每当我想使用 modelBuilder 将 ID 、 UDID 、 ApplicationKey 和 PlatformKey 定义为复合键时,它会出现以下错误。

NotificationMessageDevice_Device_Target_NotificationMessageDevice_Device_Source: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical

我认为问题是因为 NotificationMessageDevice 上的导航属性无法识别 Device 表上的主键。我该如何解决这个问题?除此之外,如果您分享您改进 Entity Framework 搜索性能的经验,我将很高兴。通常,每当我使用不带主键的 First 方法时,都会出现性能问题。

最佳答案

如果 Device 表具有复合主键,则您的 NotificationMessageDevice 表需要相同的复合外键。 SQL 如何在没有完整主键的情况下找到设备?您还应该使这些字段成为 NotificationMessageDevice 表主键的一部分。否则你不能保证主键是唯一的:

public class NotificationMessageDevice
{
    [Column(Order = 0), Key, ForeignKey("NotificationMessage")]
    public int NotificationMessage_ID { get; set; }

    [Column(Order = 1), Key, ForeignKey("Device")]
    public int Device_ID { get; set; }
    [Column(Order = 2), Key, ForeignKey("Device")]
    public string Device_UDID { get; set; }
    [Column(Order = 3), Key, ForeignKey("Device")]
    public string Device_ApplicationKey { get; set; }

    public virtual Device Device { get; set; }
    public virtual NotificationMessage NotificationMessage { get; set; }
}

关于c# - 创建复合关键 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873169/

相关文章:

c# - 首先在 Entity Framework 5代码中获取子表记录而不使用 "Include"

entity-framework-5 - EF5 枚举映射到外部类型问题

c# - 如何重置ulong中的单个位?

java - spring-data-mongodb 实体实现接口(interface)创建错误的集合

c# - EF Core 慢速批量插入(约 80k 行)

mysql - ASPNET5 .Net Core 支持 MySql EntityFramework

c# - 代码先创建表

c# - 关于用户体验的意见 - C# Winforms

c# - 在 C# 中获取视频时长、帧速率和其他属性

c# - 为什么反射会为 lambda 返回如此奇怪的名称?