Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何同时创建一对多和一对一EF Core_C#_Entity Framework_Entity Framework Core - Fatal编程技术网

C# 如何同时创建一对多和一对一EF Core

C# 如何同时创建一对多和一对一EF Core,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,用通俗易懂的英语: Room(主体实体)具有RoomPrice(从属实体)。这似乎是一对一的关系。不过,我也想保留房价变动的历史记录 当我创建一对一关系时,ef核心迁移会创建一个明显唯一的索引,以确保不会为同一个房间创建多个RoomPrice 不知何故,我实际上希望能够为一个房间创建多个房间价格(并保留历史记录),但只有一个房间价格可以引用到房间 比如说: public class Room { public int Id { get; set; } public string

用通俗易懂的英语:

Room(主体实体)具有RoomPrice(从属实体)。这似乎是一对一的关系。不过,我也想保留房价变动的历史记录

当我创建一对一关系时,ef核心迁移会创建一个明显唯一的索引,以确保不会为同一个房间创建多个RoomPrice

不知何故,我实际上希望能够为一个房间创建多个房间价格(并保留历史记录),但只有一个房间价格可以引用到房间

比如说:

public class Room
{
    public int Id { get; set; }
    public string Number { get; set; }
    public RoomPrice RoomPrice { get; set; } // current room price
    public int? RoomPriceId { get; set; } // current room price id
    public ICollection<RoomPrices> RoomPrices { get; set; }
}

public class RoomPrice
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime CreationTime { get; set; }
    public int RoomId { get; set; }
}
公共教室
{
公共int Id{get;set;}
公共字符串编号{get;set;}
公共房间价格RoomPrice{get;set;}//当前房间价格
public int?RoomPriceId{get;set;}//当前房价id
公共ICollection RoomPrices{get;set;}
}
公务舱房价
{
公共int Id{get;set;}
公共十进制数{get;set;}
公共日期时间CreationTime{get;set;}
public int RoomId{get;set;}
}
但不知何故,上述迁移可以创建表。但是,添加新文件室会引发以下异常:

INSERT语句与外键约束冲突 “FK_Rooms_RoomPrices_RoomPriceId”。数据库中发生冲突 “测试”,表“dbo.RoomPrices”,列“Id”

ef core对此有何定义?我如何在fluent api或data annotation中建立这种关系


或者我完全弄错了,我应该实施一对多关系,通过CreationTime获取最新条目作为房间的活动/当前房价

似乎您真的希望价格成为房间的一个属性,然后保存同一房间版本的历史记录。你会有一把复杂的钥匙,上面有某种ID加上日期戳来识别房间的每个版本。这可能比通常现成支持的场景更高级。我通过中断事务使其工作。第一个工作单元创建房间价格为空的房间。第二个事务添加房间价格,然后更新房间属性以设置房间价格。