简体   繁体   English

C Sharp Object仅在另一个类中创建和引用一个对象

[英]C Sharp Object creating and referencing only 1 object in another class

I need to implement 1..* and 1..1 relationships in a store scenario application.(Classes: Member, Order, OrderLine, Product, Program, User) How do i go about a 1 user only having 1 Order that can have many OrderLines (preferably using a List structure? 我需要在商店场景应用程序中实现1 .. *和1..1关系。(类:成员,订单,OrderLine,产品,程序,用户)我如何处理只有1个订单可以拥有的1个用户许多OrderLines(最好使用List结构?

This is my User class: 这是我的用户类:

namespace ConsoleApplication1
{
    public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
        public User() {}

        //Overrides
        public override bool Equals(object obj)
        {
            return obj.ToString() == this.ToString();
        }
        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }
        public override string ToString()
        {
            string myUser;
            myUser = string.Format("First Name: {0}; Last Name: {1}", fName, lName);
            return myUser;     
        }

        // Properties
        public string fName
        {
            get
            {
                return ffName;
            }
            set
            {
                ffName = value;
            }
        }
        public string lName
        {
            get
            {
                return llName;
            }
            set
            {
                llName = value;
            }
        } 
    }
}

You have to implement the Order and the OrderLine class as: 您必须将OrderOrderLine类实现为:

class OrderLine
{
      //some code
}


class Order
{
     List<OrderLine> lstOrderLine;

     //some code
}

Then add the Order class to your user class. 然后将Order类添加到您的用户类。

You can have an Order class and an OrderLine class. 您可以拥有Order类和OrderLine类。 The Order class will have a List of OrderLines and the User class can have a Order member. Order类将具有OrderLines列表,User类可以具有Order成员。

Something like: 就像是:

public class User
    {

        private string ffName;
        private string llName;
        private int id = 0;
        private Order order = null;

        //Constructor
        public User(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
...
}

public class Order
{
 List<OrderLine> orderLines = null;
}

public class OrderLine
{
}

Edit: Removed snarkyness and attitude :) 编辑:删除snarkyness和态度:)

First you need an order (hint you are going to need a class for that). 首先你需要一个订单(暗示你需要一个类)。 Now the order needs to be attched to a user. 现在订单需要附加到用户。 So add a field of type User. 因此,添加User类型的字段。 That takes care of one order one user. 这照顾一个订单一个用户。 (Note that a user can make more than one order) (请注意,用户可以生成多个订单)

So now you order is missing lines. 所以现在你的订单缺少了。 Add another member variable that is a list of line types. 添加另一个成员变量,该变量是行类型列表。 Now in your order you need to add methods to add, remove and query order lines. 现在,在您的订单中,您需要添加添加,删除和查询订单行的方法。

Edit: The question was raised what was meant by "add a field". 编辑:提出了“添加字段”的含义。 Add a field means add a property or private member. 添加字段意味着添加属性或私有成员。 When you are doing this you are doing the technical term of composition. 当你这样做时,你正在做组成的技术术语。 Composition is commonly explained as a "has a" relationship. 组成通常被解释为“具有”关系。 So an order "has a user" and "has a list of order lines" 所以订单“有一个用户”和“有一个订单行列表”

Class User()
{
    public string firstName { get; set; }
    public string lastName {get; set; }
    public int id { get; set;}
}

Class OrderLine()
{

}

Class Order()
{
    private List<OrderLine> orderLines;
    public User submitter { get; set;}

    public Order()
    {
         orderLines = new List<OrderLine>();
    }

    public void AddOrderLine(OrderLine newOrderLine)
    {
         this.orderLines.Add(newOrderLine);
    }

    public IList<OrderLine> GetOrderLines()
    { 
         return this.orderLines;
    }
}

Example

User customer1 = new User();
// Initialize customer1 values...
Order someOrder = new Order();
someOrder.submitter = customer1;
someOrder.AddOrderLine(new OrderLine());

EDIT: Changed Member class to User class 编辑:将成员类更改为用户类

Your most recent comment cleared up your question: 您最近的评论澄清了您的问题:

Its not hard to create each one i just dont understand how to get the relationship to work with 1..* or 1..1. 创建每一个并不难,我只是不明白如何让关系与1 .. *或1..1一起工作。 If i create an Order i can always create another order 如果我创建订单,我总是可以创建另一个订单

So, let's talk about the types of relationships. 那么,我们来谈谈关系的类型。

Relationship types 关系类型

Relationship types don't talk about absolute numbers of entities in the system. 关系类型不涉及系统中实体的绝对数量。 They just talk about numbers of entities in relation to other entities. 他们只是谈谈对于其他实体的实体的数量。

1:1 Relationship 1:1的关系

This means that the two entity types must exist in pairs. 这意味着两个实体类型必须成对存在。 If one entity of type A exists, then only one entity of type B can exist. 如果存在一个类型A的实体,则只能存在一个类型B的实体。 For example, your User and Order . 例如,您的UserOrder An order can't exist without a User , and a User can only have one Order . 没有User ,订单就不能存在, User只能有一个Order This doesn't mean there is only one User - there could be 42 users . 这并不意味着只有一个User - 可能有42个用户 This just means that if an Order exists, a User must also exist, and that the User can only have one Order . 这只是意味着如果存在Order ,则User也必须存在,并且User只能拥有一个Order

There is a strict and less strict version of this. 对此有一个严格且不太严格的版本。 Technically, I just described something like a 1:{0 or 1} relationship. 从技术上讲,我刚刚描述了类似于1:{0或1}的关系。 In a real 1:1 relationship you would require that the Order exists if the User exists. 在真实的1:1关系中,如果User存在,您将要求 Order存在。 Neither could exist if the other didn't exist. 如果对方不存在,也不会存在。 However this constraint is usually relaxed when talking about relational databases (but only in one direction - in this case you still can't have an Order without a User ). 但是,在谈论关系数据库时,这种约束通常会放松(但只能在一个方向上 - 在这种情况下,如果没有User您仍然无法拥有Order )。

You can model this relationship with code like this: 您可以使用以下代码对此关系建模:

public class User
{
    public Order Order { get; set; }
}

public class Order
{
    // You could put a reference here back to the User if you want...
}

Note that it is a bit weird to only support only one Order for a User . 请注意,仅为User仅支持一个Order User It makes more sense to make it 1:* . 使它成为1:*更有意义。 But if that is a requirement of your assignment, then this is how you'd model it. 但如果这是你的任务的要求,那么这就是你的模型。

1:* Relationship 1:*关系

This is similar to the 1:1 relationship. 这类似于1:1的关系。 But it relaxes some of the restrictions so that if an entity of type A exists, then any number (including zero) of type B can exist. 但它放宽了一些限制,因此如果存在类型A的实体,则可以存在任何类型B(包括零)的类型。 The example is the Order and OrderLine . 例子是OrderOrderLine Again, there is no restriction on how many of either entity type exist. 同样,对于存在多少实体类型没有限制。 There could be 57 orders in the system. 系统中可能有57个订单 You just can't have an OrderLine without an Order , and there could be multiple OrderLine s per Order . 如果没有Order ,您就不能拥有OrderLine ,每个Order可能有多个OrderLine

You can model this relationship with code like this: 您可以使用以下代码对此关系建模:

public class Order
{
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    // You could put a reference here back to the Order if you want...
}

Enforcing relational concepts in code 在代码中强制执行关系概念

I can't speak for your assignment, so make sure you back up what I am saying here against what your assignment requires. 我不能代表你的任务,所以请确保你支持我在这里所说的内容,反对你的任务要求。

You should not try to enforce basic relational concepts like these in code. 您不应该尝试在代码中强制执行这些基本关系概念。 The database is better at it, has better (declarative) language to describe the relationships, and is going to be your ultimate source of data for the system. 数据库更好,有更好的(声明性)语言来描述关系,并且将成为系统的最终数据源。

Instead, you should just do a soft model that follows the relationships (as the code samples above do), and let the database do the real policing of those constraints. 相反,你应该只做一个遵循关系的软模型(如上面的代码示例所做的那样),让数据库对这些约束进行真正的监管。

Examples: 例子:

  • You should not try to restrict construction of Order types in code, and you shouldn't require a User to exist to construct an Order (as code entities). 您不应该尝试在代码中限制Order类型的构造,并且您不应该要求User存在来构造Order (作为代码实体)。
  • You should not require an Order to exist to create an OrderLine (as code entities). 您不应该要求存在Order来创建OrderLine (作为代码实体)。

Trying to put these sorts of restrictions in code buys you nothing. 试图在代码中加入这些限制只会给你带来任何好处。 When you persist the entities to the database, the database will ensure these relationships for you (assuming you've set it up correctly, which you will learn to do). 当您将实体持久保存到数据库时,数据库将为您确保这些关系(假设您已正确设置它,您将学会这样做)。 Your error will be caught, and you'll learn habits that avoid these types of errors very quickly. 您的错误将被捕获,您将学习很快避免这些类型错误的习惯。

Trying to put these sorts of restrictions in code hurts you. 试图在代码中加入这些限制会伤害你。 It will be harder to write your program, and it will be harder to write unit tests for your code. 编写程序会比较困难,为代码编写单元测试会更困难。

For example, consider an algorithm or test that compares OrderLine values. 例如,考虑比较OrderLine值的算法或测试。 Maybe you want it to compare to a hypothetical OrderLine . 也许您希望它与假设的 OrderLine进行比较。 If you had relational restrictions in place in your code, you'd also have to create a hypothetical Order and User . 如果您的代码中存在关系限制,则还必须创建一个假设的OrderUser Would you also compare the hypothetical User and Order to the real ones? 您是否还将假设的UserOrder与真实的UserOrder进行比较? What if your algorithm shouldn't care what User or Order it originated from? 如果您的算法不关心它来自哪个UserOrder怎么办? If you're not going to compare them, why bother creating them to begin with? 如果你不打算比较它们,为什么要开始创建它们呢?

So: Don't worry about it. 所以:别担心。 Softly model your relationships so that it is easy to navigate between your objects, and let the database do your strict relationship validations for you. 轻松地建立关系模型,以便在对象之间轻松导航,让数据库为您进行严格的关系验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM