c# - 如何建模这个实体

标签 c# asp.net-mvc entity-framework ef-code-first scaffolding

我正在为一家商店创建一个应用程序,其中客户分为两组:收款人和付款人。

1) 许多收款人可能与同一个付款人有关。 2) 付款人本身可以是收款人,因此他只与一个收款人相关

到目前为止,我的代码如下所示:

public class Receiver
{
    [Key]
    public int ReceiverId { get; set; }
    public string Name { get; set; }
    [Required]
    public int PayerId { get; set; }
    public virtual Payer Payer { get; set; }
}

public class Payer
{
    [Key]
    public int PayerId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Receiver> Receivers { get; set; }
}

但是我需要让用户创建一个同时也是接收方的新付款方,因此接收方集合将只有一个元素。为此,我想使用一个复选框,它将被转换为数据库中的一个新列 (IsAlsoReceiver)。

我正在使用 MVC 脚手架创建 View ,它创建了两个 View 用于添加 Receiver 和另一个 View 用于添加 Payer。当用户需要同时也是接收方的付款方时,他必须在两个 View 中添加实体;在这种情况下可以简化吗?

我要求一个聪明的方法来做到这一点。

最佳答案

我认为您缺少抽象层。当您构建一个特定规模(我认为您已经达到的规模)的项目时,您需要每个组件(数据层、逻辑层和 View )来查看不同的模型。

数据访问层 (DAL) 具有领域模型

逻辑层或 API 具有数据传输对象

View 有 View 模型

为了便于构建和理解,我只使用域模型和 View 模型。

对于您当前的问题,我会像这样构建它:

//this is the view model
//The user sees this model
public class Person {
    public string Name { get; set; }
    public bool IsReceiver { get; set; }
    public bool IsPayer { get; set; }
}
//these are the domain models
//The database uses these models
public class Receiver {
    [Key]
    public int ReceiverId { get; set; }
    public string Name { get; set; }
    [Required]
    public int PayerId { get; set; }
    public virtual Payer Payer { get; set; }
}
public class Payer {
    [Key]
    public int PayerId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Receiver> Receivers { get; set; }
}

public class AccountController {

    //create a view for the Person View Model
    //this is your abstraction
    public void SignUp(Person p) {
        //create models for the repository
        Payer payer = new Payer() {
            Name = p.Name
        };
        Receiver receiver = new Reciever() {
            Name = p.Name
        };

        //if the payer is his own receiver:
        Receiver.Payer = payer;

        //if the payer is his own receiver:
        Payer.Receivers.Add(receiver);


        //create for each depending upon some condition
        //I've just allowed the user to select whether he is a payer
        //based upon a checkbox on the form I suppose
        if (p.IsPayer) {
            db.Payers.Add(payer);
        }
        if (p.IsReceiver) {
            db.Receivers.Add(receiver);
        }

        db.SaveChanges();
    }
}

关于c# - 如何建模这个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25227339/

相关文章:

c# - 如何通过 PHP 调用 C# web 服务?

c# - 如何从 LINQ to Entities 获取唯一值?

c# - 如何从文本框上的COM端口写入数据?,C#MVC 4, Razor

c# - 从 KeyMembers 中获取身份字段

c# - 从 SQL(C# 和 Entity Framework )到 mongodb(Go 和 mgo)

mysql - 无法删除 MySQL 中带有外键的列

c# - 使用 ItextSharp PdfPTable,table.TotalHeight 返回 0.0,但期望为正浮点值

c# - 我可以在 asp.net core 上运行 C# 游戏吗?

asp.net-mvc - 如何将模型绑定(bind)到 List<ViewModel>?

c# - MVC5单选按钮值错误