gpt4 book ai didi

c# - Entity Framework - 重用复杂类型

转载 作者:太空狗 更新时间:2023-10-29 21:23:56 24 4
gpt4 key购买 nike

我在 Code First Entity Framework 中有一个实体,目前看起来像这样:

public class Entity
{
// snip ...

public string OriginalDepartment { get; set; }
public string OriginalQueue { get; set; }

public string CurrentDepartment { get; set; }
public string CurrentQueue { get; set; }
}

我想像这样为这些类型创建复杂类型:

public class Location
{
public string Department { get; set; }
public string Queue { get; set; }
}

我想对 Current 和 Original 使用相同的类型:

public Location Original { get; set; }
public Location Current { get; set; }

这可能吗,还是我需要创建两个复杂类型 CurrentLocationOriginalLocation

public class OriginalLocation
{
public string Department { get; set; }
public string Queue { get; set; }
}

public class CurrentLocation
{
public string Department { get; set; }
public string Queue { get; set; }
}

最佳答案

开箱即用,您无需创建两个复杂类型。

您还可以使用模型构建器显式配置复杂类型

modelBuilder.ComplexType<Location>();

要自定义列名,您应该从父实体配置中配置它们

public class Location
{
public string Department { get; set; }
public string Queue { get; set; }
}

public class MyEntity
{
public int Id { get; set; }
public Location Original { get; set; }
public Location Current { get; set; }
}

public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<Location>();

modelBuilder.Entity<MyEntity>().Property(x => x.Current.Queue).HasColumnName("myCustomColumnName");
}
}

这会将 MyEntity.Current.Queue 映射到 myCustomName

关于c# - Entity Framework - 重用复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931341/

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