【问题标题】:Using Entity Framework for relating 3 entitites where 1 of them can only be related to either one of remaining two使用实体框架关联 3 个实体,其中 1 个实体只能与其余两个实体中的任何一个相关
【发布时间】:2019-11-22 14:49:24
【问题描述】:

假设我有两个实体,bungalowsapartments。它们都有不同的字段并且不能互换,但是这两个实体都有多个租户。每个租户只能是一间平房或一间公寓的一部分。如何使用 Entity Framework 实现这一点?

我正在考虑再创建 2 个实体 bungalowTenantsapartmentTenants 并使用它们进行映射。每个bungalowTenant 将有一个bungalowtenant 的实例,apartmentTenant 的实例也是如此。

Bungalows 会有 bungalowTenants 和 apartmentTenants 的集合。

public class Bungalow
{        
        public int Id { get; set; }
        public int HouseNumber { get; set; }
        public string Street { get; set; }
        public ICollection<BungalowTenants> Tenants { get; set; }
}

public class Apartment
{        
        public int Id { get; set; }
        public int ApartmentNumber{ get; set; }
        public string Wing{ get; set; }
        public string Building{ get; set; }
        public ICollection<ApartmentTenants> Tenants { get; set; }
}

public class Tenant
{        
        public int Id{ get; set; }
        public string Name{ get; set; }
}

public class ApartmentTenants
{        
        public int ApartmentId { get; set; }
        public Apartment Apartment{ get; set; }
        public int TenantId{ get; set; }
        public Tenant Tenant{ get; set; }
}

public class BungalowTenants
{        
        public int BungalowId{ get; set; }
        public Bungalow Bungalow{ get; set; }
        public int TenantId{ get; set; }
        public Tenant Tenant{ get; set; }
}

这种方法的问题在于,它不会以任何方式限制同一租户同时成为平房和公寓的一部分。我无法弄清楚如何使用实体框架来做到这一点。对于此事,我将不胜感激。

【问题讨论】:

    标签: c# asp.net .net entity-framework asp.net-core


    【解决方案1】:

    并非每个业务规则都可以或需要转换为数据库约束或模型约束。

    如果您通过模型规则或编程规则强制执行此操作:

    如果租户决定从平房到公寓怎么办?他们很可能希望在旧房取消日期前几天甚至几周开始租用新房——或者您是否希望他们在午夜前搬出旧房并在午夜后进入新房,并收拾好所有物品人行道上的箱子一段时间?这似乎不太现实。

    【讨论】:

    • 嗨,这只是一个例子。我需要的实际上太具体了,因此我使用了一个类比。
    • 通过应用程序逻辑,我可以确保不会发生重复,但我想检查是否可以在数据库级别完成。我也找到了一个使用纯 SQL 的解决方案,但无法将其转换为实体框架。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多