gpt4 book ai didi

c# - 多对可选关系是否可能?

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:05 24 4
gpt4 key购买 nike

我遇到以下情况:一个Device 可以有多个Subscriptions,但是一个Subscription 最多有一个Device 或者根本没有。在我的数据库中 Subscriptions 有一个外键 DeviceIDNullable (不是 Device 中的 ID 属性 类)。目前由于某种原因,以下流畅的代码有效:

            modelBuilder.Entity<Device>()
.HasMany(e => e.Subscriptions)
.WithRequired(e => e.Device)
.WillCascadeOnDelete(false);

如果我选择 WithOptional(),这应该是合乎逻辑的,我会得到错误。错误是这个 ModelvalidationError:

Additional information: One or more validation errors were detected during model generation:

Entities.Device_Subscriptions: : Multiplicity conflicts with the referential constraint in Role 'Device_Subscriptions_Source' in relationship 'Device_Subscriptions'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

但是,如果我现在查询(使用 .WithRequired(...) 代码)

db.Subscriptions.Where(s => s.DeviceID == null).Count();

我得到零,尽管我的数据库中有一个 SubscriptionDeviceID 为 null。

设备的(部分)模型:

public class Device
{
public Device() : base()
{
Subscriptions = new HashSet<Subscription>();
}
[Key]
public decimal DeviceID { get; set; }

public virtual ICollection<Subscription> Subscriptions {get; set;}
}

订阅的(部分)模型:

public partial class Subscription
{
[Key]
[Column(Order = 0)]
public decimal? DeviceID { get; set; }

[Key]
[Column(Order = 1)]
[StringLength(50)]
public string Type { get; set; }

public virtual Device {get; set;}
}

最佳答案

[Key] 属性用于声明实体的主键。将可空值作为 PK 的一部分实际上没有意义。

从评论来看,您真正想要完成的似乎是在 (DeviceID, Type) 上建立索引。在 EF 6.1 中,他们添加了应该完成此操作的 [Index] 属性。 Reference

关于c# - 多对可选关系是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com