gpt4 book ai didi

c# - 在 Entity Framework 6 中使用规范化数据?

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

假设我有这两个实体,一个帐户实体有一个地址。

public class Address
{
public int Id { get; private set; }
public string Address1 { get; private set; }
public string Address2 { get; private set; }
public string Address3 { get; private set; }
public int PostalCodeId { get; private set; }

public virtual PostalCode PostalCode { get; private set; }
}

public class PostalCode
{
public int Id { get; set; }
public string ZipCode { get; set; }
}

我正在使用 CQRS,并且有一个命令可以像这样更改地址。

public bool ChangeAddress(int addressId, string line1, string line2, string line3, string zipCode)
{
//do something here....
}

我正在为如何管理它而苦苦挣扎。由于我们已经规范化了数据,被更改的地址可能会用在 5 个地方。我们可以在此处应用 3 个工作流程。

  1. Simply change the address, meaning all 5 places would be using the updated address.
  2. Prompt the user, letting them know this address is used in 5 places, and have them specify if they want to change all or just this one (a lot more work).
  3. Change just the address for this specific account, thus meaning we have 2 different addresses persisted in the db store now, the new one, and the old one which is now used in 4 places.

首选工作流程是什么(是的,我知道没有正确答案,我想知道通常会做什么)?

一旦确定了工作流程,将如何实现。例如,以上面的案例 1 为例。要实现更改,我必须执行以下操作:

  1. Instantiate an address object in code using the parameters to the method.
  2. Look in the DB to see if that address exists.

    a. [If Exists] - get Id of existing, set Account.AddressId = foundId
    b. [If doesn't Exist] - use instantiated object and assign, Account.Address = newAddress, then .SaveChanges() and a new address record will be entered into the database.

..看起来工作量很大,但也许就是这样。

此外,如果用户只是更改他们正在更改的地址上的邮政编码会怎样。我需要先查看数据库中是否存在"new"的,然后使用它的 ID。如果不存在,则在代码中实例化一个新对象。 id 将为 0,因此 EF 在 .SaveChanges() 上设置 EntityState.Inserted,一条新记录将被放置在表中。然后......我必须查找旧的,如果它不再在任何地方使用,请将其从数据库中删除。

..更多的工作,但同样,也许它就是这样。

我是不是遗漏了什么,看起来像这样的事情应该使用 ORM 更容易做到。

最佳答案

本地址被更改(编辑)时,应该是为了更正地址,因此它应该只在一个地方更改,并在所有引用它的地方反射(reflect)出来。 IOW 它应该在所有这 5 个地方改变。如果它是一个人独有的东西,比如电子邮件地址,那么它就不会在另一个表(实体)上。

根据需要,它可以建模为一对一、一对多或多对多。

class Person
{
public Address Address {get;set;}
}

class Person
{
public virtual ICollection<Address> Addresses {get;set;}
}

class Address
{
...
}

//or
class Address
{
...
public virtual ICollection<Person> People {get;set;}
}

关于c# - 在 Entity Framework 6 中使用规范化数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32891374/

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