简体   繁体   中英

How to read two entities from single text file using filehelpers or other library in C#

Text file contains order and order detail lines. First line in order header. After that there is variable number of detail lines. After detail there is blank line followed by next order etc. For order line first field is order number. For detail line first field is 1 always.

128502 02.01.2012 20120 02.01.2012
1   Wine    0   1300
1   Meat    5,8333  5,83

128503 02.01.2012 20123 02.01.2012  
1   Wine    20  130
1   Meat    1,33    283,23
1   Cow 2,333   333,23

....

This file need to be readed into list of entities:

class Order {
  public string Number; // order number from first field, primary key 
  public string Date;
  ... other fields  
}


class OrderDetails {
  public string Number; // order number from previous line , foreign key to Order
  public string ProductName;
  ... other fields  
}

(Instead on Number custom integer id column can also used for relation)

How to read such file in C# ASP.NET MVC2 using FileHelpers library or other way ?

Update

sample

http://www.filehelpers.com/example_multirecords.html

referenced from

Multiple CSV strutures with FileHelpers

shows how to read two tables. How to create relation between those tables: During reading foreign key to order column should added to details table. How to implement this, getting last order number from previous order line and annd it to detail record ?

Well you could go brute force all in one go. Read in the entire file Split on the blank like. Create an Order out of the first line of each split Create details out of the rest.

If the files are huge then you could read in up to each blank line and then process as above.

Another solution that might have some advantages.

Run the file through a process that edit's the detail line and adds in the order number from it's realted order line. Then another that splits out order and detail into two separate files. Then process orders then details without having to worry about all this dittoing and two structures.

Fourth solution, is give whoever came up with this format a good beating to encourage them to do it properly...

There's no magic wand solution for this, the file format is simply wholly unsuitable for any efficent passing of data to something that might store it sensibly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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