【问题标题】:Entity Framework How to have relationship between two columns of two tables实体框架如何在两个表的两列之间建立关系
【发布时间】:2019-12-02 03:39:11
【问题描述】:

有两个实体 A 和 B。它们具有一对多的关系。 假设 A 为以下类型。

class A
{
        public int Id { get; set; }
        public bool isActive{ get; set; }
        public ICollection<B> BCollection{ get; set; }
        //Rest Of A properties
}

class B
{
        public int Id { get; set; }
        public A A{ get; set; }
        public int AId{ get; set; }
        public bool isAActive{ get; set; }
        //Rest of B Properties
}

B中的S AId是A中的主键Id的外键。由于B中有A实例,本实体框架自行配置。

有没有一种方法可以通过实体框架配置我的 DBSet,以便根据 A 中 isActive 的值自动设置 isAActive 的值?

【问题讨论】:

  • 我没有办法从流利的 api 或属性绑定中设置它,但你可能想查看像 Automapper 这样的对象映射器来帮助你。这个链接可能会让你感兴趣。 “stackoverflow.com/questions/6872610/…”。它使用急切加载来更新 id。你可以用 isAActive 替换。
  • 我认为你的实体应该尽可能地映射到数据库模式,否则你代表的是非规范化。您要描述的内容看起来像“域模型”,它应该代表系统或业务域的更好版本[因为数据库/实体模型受数据库设计原则的约束]。
  • 在我看来B.IsAActiveB.A.isActive 的值相同,您可以从导航属性中获取IsAActive

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


【解决方案1】:

不确定这是否是您正在寻找的东西,但使用构造函数可能会有所帮助

public  class A
{
    public int id { get; set; }
    public bool isActive { get; set; }
    public List<B> BCollection { get; set; }
}

public class B
{
    public B (A a){
        isAActive = a.isActive;
        }
    public int id { get; set; }
    public A A { get; set; }
    public bool isAActive { get; set; }
}

static void Main(string[] args)
{
    A a = new A()
    {
        id = 1,
        isActive = true
    };
    A a2 = new A()
    {
        id = 2,
        isActive = false
    };

    List<B> bs = new List<B>()
    {
        new B(a) { id = 100, A = a},
        new B(a) { id = 200, A = a}
    };
    a.BCollection = bs;

    List<B> bs2 = new List<B>()
    {
        new B(a2) { id = 300, A = a2},
        new B(a2) { id = 300, A = a2}
    };
    a2.BCollection = bs2;

    return;
}

a.BCollection 会将 isAActive 设置为 true
a2.BCollection 将 isAActive 设置为 false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多