LINQ to sQL:业务层多个Class Library,or 只用一个?

黄汉 2009-10-15 10:28:51
在公司内部某系统的开发过程中,为了让公司里另外一个业余编程人员参与开发,在设计的时候特意考虑降低代码结构的复杂度。在实现业务层的时候,我告诉他对每一个单独的业务单元创建一个新的Class Library,在每个Class Library中建立自己的LINQ to SQL class(DBML)。

现在发现这样的结构有一个问题,就是很难统一每个DBML文件所使用的的ConnectionString。因为都是单独设定的。虽然在网上包括MSDN、StackOverflow上看到了一些相关的问题,例如“Multiple LINQ to SQL Classes or one”?但是这些问题的前提都是多个DBML存在于一个Class Library中。

我们的系统其实并不复杂,只使用了一个数据库,表格数目不超过100个。

那么究竟是使用多个Class Library,还是一个呢?

I went to msdn and asked the question:

My ASP.net application uses only 1 sql server 2000 database and no more than 50 tables in it. And I copied an instance of the database to run on my develop PC, so I need to switch the connections between dev and release.
the problem is, i had created multiple class libraries in business layer, each class library has a LINQ to SQL class. now I find it difficult to make all dbml files in different projects use the same connection string. so is my design wrong? Should i only use 1 class library? then if remain to use multiple class libraries, how to ensure the same connectionstring is used when release?

其实这个问题还是“业务层怎么实现”的问题。也就是说,我是不是考虑的太狭隘了,将原本不需要划分成多个class library Peoject的东西“琐碎”化了?
...全文
198 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
weilai2800 2012-02-12
  • 打赏
  • 举报
回复
一个或者多个,只要能很好的处理,都无妨!
  • 打赏
  • 举报
回复
是不是时代不同了,搞软件的没有几个正规学过软件工程了?

软件工程中最古老的做法,最入门(甚至过时)的知识,就是告诉你应该合理划分模块。难道一切都要从头学起?
  • 打赏
  • 举报
回复
一个系统,你可以看作就是一个系统,也可以看作是几个子模块(甚至几个子系统)。

这是全在于你的决断,这有什么纠结的呢?

“业务单元”使用同一个数据库,或者各自使用10个数据库,有什么关系在接口上“统一”呢?这些根本不影响业务的接口,这些顶多影响到你的配置文件中是只有一条配置信息还是多条配置信息这种底层实现的层面上。
anzhiqiang_touzi 2012-01-03
  • 打赏
  • 举报
回复
建议:从新包装DataContext禁止缓存跟踪,建立Dao层+实体层+业务处理层+AOP(每个业务逻辑使用一次DataContext,使用完成回收,如果再使用的话就New一个)
xray2005 2009-10-17
  • 打赏
  • 举报
回复
有点烦琐.

你必要一个一个lib啊. 类似的业务可以放一个lib.分类处理一下.


就像衣服的尺码一样,小,中,大,加大等几号,也没见哪个做服装的,按照0-300cm,每个厘米都做一个套吧.

yixianggao 2009-10-17
  • 打赏
  • 举报
回复
那么究竟是使用多个Class Library,还是一个呢?

lz 提出这个问题时就已经有答案,又何必问呢?!

很明显,用一个!!!

为啥?因为 lz 现在用了多个很不爽,否则也就不发此贴了!

软件开发一定要爽,觉得不爽时肯定有问题,需要改变某些东东!
黄汉 2009-10-16
  • 打赏
  • 举报
回复
William Wegerson (www.OmegaCoder.Com)给我的回复:

You need to centralize in each layer a single point of access. Meaning each layer has one DBML connection. One option is to use a singleton pattern to return the datacontext to be used within the layer. That singleton will be responsible for choosing the appropriate connection string to use and the code that consumes the data will be no wiser.
Beginning: Microsoft Visual C# 2008 0 About the Authors 9 Credits 10 Contents 12 Introduction 30 Who This Book Is For 30 How This Book Is Structured 31 What You Need to Use This Book 34 Conventions 34 Source Code 35 Errata 35 p2p.wrox.com 36 Part I: The C# Language 38 Chapter 1: Introducing C# 40 What Is the .NET Framework? 40 What Is C#? 45 Visual Studio 2008 46 Summary 48 Chapter 2: Writing a C# Program 50 The Development Environments 51 Console Applications 55 Windows Forms Applications 61 Summary 66 Chapter 3: Variables and Expressions 68 Basic C# Syntax 69 Basic C# Console Application Structure 71 Variables 73 Expressions 83 Summary 93 Exercises 94 Chapter 4: Flow Control 96 Boolean Logic 96 The goto Statement 106 Branching 107 Looping 115 Summary 127 Exercises 127 Chapter 5: More About Variables 130 Type Conversion 130 Complex Variable Types 140 String Manipulation 155 Summary 160 Exercises 161 Chapter 6: Functions 162 Defining and Using Functions 163 Variable Scope 175 The Main() Function 181 Struct Functions 184 Overloading Functions 185 Delegates 187 Summary 190 Exercises 191 Chapter 7: Debugging and Error Handling 192 Debugging in VS and VCE 193 Error Handling 213 Summary 221 Exercises 221 Chapter 8: Introduction to Object-Oriented Programming 222 What Is Object-Oriented Programming? 223 OOP Techniques 229 OOP in Windows Applications 240 Summary 243 Exercises 243 Chapter 9: Defining Classes 246 Class Definitions in C# 246 System.Object 253 Constructors and Destructors 255 OOP Tools in VS and VCE 260 Class Library Projects 266 Interfaces Versus Abstract Classes 270 Struct Types 272 Summary 275 Exercises 276 Chapter 10: Defining Class Members 278 Member Definitions 278 Additional Class Member Topics 291 Interface Implementation 294 Partial Class Definitions 299 Partial Method Definitions 301 Example Application 302 Summary 313 Exercises 313 Chapter 11: Collections, Comparisons, and Conversions 314 Collections 314 Comparisons 340 Conversions 363 Summary 365 Exercises 366 Chapter 12: Generics 368 What Is a Generic? 368 Using Generics 370 Defining Generics 388 Summary 405 Exercises 405 Chapter 13: Additional OOP Techniques 408 The :: Operator and the Global Namespace Qualifier 408 Custom Exceptions 410 Events 412 Expanding and Using CardLib 426 Summary 434 Exercises 435 Chapter 14: C# 3.0 Language Enhancements 436 Initializers 437 Type Inference 443 Anonymous Types 445 Extension Methods 449 Lambda Expressions 455 Summary 466 Exercises 467 Part II: Windows Programming 468 Chapter 15: Basic Windows Programming 470 Controls 471 The Button Control 477 The Label and LinkLabel Controls 480 The TextBox Control 481 The RadioButton and CheckBox Controls 491 The RichTextBox Control 498 The ListBox and CheckedListBox Controls 506 The ListView Control 512 The TabControl Control 523 Summary 528 Exercises 529 Chapter 16: Advanced Windows Forms Features 530 Menus and Toolbars 531 Toolbars 538 SDI and MDI Applications 549 Creating Controls 561 Summary 572 Exercises 572 Chapter 17: Using Common Dialogs 574 Common Dialogs 574 How to Use Dialogs 576 File Dialogs 577 Printing 596 Print Preview 612 FontDialog and ColorDialog 614 Summary 618 Exercises 619 Chapter 18: Deploying Windows Applications 620 Deployment Overview 620 ClickOnce Deployment 621 Visual Studio Setup and Deployment Project Types 634 Microsoft Windows Installer Architecture 635 Creating an Installation Package for the SimpleEditor 639 Building the Project 654 Installation 654 Summary 659 Exercises 660 Part III: Web Programming 662 Chapter 19: Basic Web Programming 664 Overview 665 ASP.NET Runtime 665 Creating a Simple Page 666 Server Controls 673 Event Handlers 674 Input Validation 679 State Management 683 Authentication and Authorization 689 Reading and Writing to an SQL Server Database 697 Summary 706 Exercises 707 Chapter 20: Advanced Web Programming 708 Master Pages 708 Site Navigation 716 User Controls 717 Profiles 720 Web Parts 725 JavaScript 738 Summary 744 Exercises 745 Chapter 21: Web Services 746 Before Web Services 747 Where to Use Web Services 748 Web Services Architecture 751 Web Services and the .NET Framework 754 Creating a Simple ASP.NET Web Service 757 Testing the Web Service 759 Implementing a Windows Client 761 Calling the Service Asynchronously 765 Implementing an ASP.NET Client 768 Passing Data 769 Summary 773 Exercises 774 Chapter 22: Ajax Programming 776 Ajax Overview 776 Update Panel 778 Timer Control 783 Update Progress 784 Web Services 786 Extender Controls 792 Summary 794 Exercises 794 Chapter 23: Deploying Web Applications 796 Internet Information Services 796 IIS Configuration 797 Copying a Web Site 800 Publishing a Web Site 802 Windows Installer 804 Summary 809 Exercises 810 Part IV: Data Access 812 Chapter 24: File System Data 814 Streams 815 The Classes for Input and Output 815 Serialized Objects 842 Monitoring the File Structure 847 Summary 855 Exercises 855 Chapter 25: XML 856 XML Documents 856 Using XML in Your Application 865 Summary 884 Exercises 885 Chapter 26: Introduction to LINQ 886 LINQ Varieties 887 First LINQ Query 887 Using the LINQ Method Syntax and Lambda Expressions 892 Ordering Query Results 895 orderby Clause 897 Ordering Using Method Syntax 897 Querying a Large Data Set 899 Aggregate Operators 902 Querying Complex Objects 905 Projection: Creating New Objects in Queries 909 Projection: Method Syntax 912 Select Distinct Query 912 Any and All 914 Ordering By Multiple Levels 916 Multi-Level Ordering Method Syntax: ThenBy 918 Group Queries 918 Take and Skip 920 First and FirstOrDefault 923 Set Operators 924 Joins 928 Resources and Further Reading 929 Summary 930 Exercises 930 Chapter 27: LINQ to SQL 932 Object -Relational Mapping (ORM) 933 Installing SQL Server and the Northwind Sample Data 933 First LINQ to SQL Query 935 Navigating LINQ to SQL Relationships 944 Drilling Down Further with LINQ to SQL 948 Grouping, Ordering, and Other Advanced Queries in LINQ to SQL 951 Displaying Generated SQL 954 Data Binding with LINQ to SQL 958 Updating Bound Data with LINQ to SQL 965 Summary 966 Exercises 967 Chapter 28: ADO.NET and LINQ over DataSet 970 What Is ADO.NET? 971 Overview of ADO.NET Classes and Objects 974 Reading Data with the DataReader 977 Reading Data with the DataSet 985 Updating the Database 989 Accessing Multiple Tables in a DataSet 1002 XML and ADO.NET 1010 SQL Support in ADO.NET 1014 Using LINQ over DataSet with ADO.NET 1022 Summary 1027 Exercises 1027 Chapter 29: LINQ to XML 1030 LINQ to XML Functional Constructors 1031 Saving and Loading an XML Document 1035 Working with XML Fragments 1039 Generating XML from LINQ to SQL 1041 How to Query an XML Document 1046 Summary 1053 Exercises 1053 Part V: Additional Techniques 1054 Chapter 30: Attributes 1056 What Is an Attribute? 1056 Reflection 1060 Built-in Attributes 1063 Custom Attributes 1075 Summary 1083 Chapter 31: XML Documentation 1086 Adding XML Documentation 1087 Making Use of XML Documentation 1105 Summary 1110 Exercises 1110 Chapter 32: Networking 1112 Networking Overview 1112 Networking Programming Options 1120 WebClient 1121 WebRequest and WebResponse 1123 TcpListener and TcpClient 1133 Summary 1141 Exercises 1142 Chapter 33: Introduction to GDI+ 1144 Overview of Graphical Drawing 1145 Drawing Lines Using the Pen Class 1156 Drawing Shapes Using the Brush Class 1159 Drawing Text Using the Font Class 1161 Drawing Using Images 1165 Advanced Capabilities of GDI+ 1175 Summary 1177 Exercises 1178 Chapter 34: Windows Presentation Foundation 1180 What Is WPF? 1181 Anatomy of a Basic WPF Application 1185 WPF Fundamentals 1197 Programming with WPF 1237 Summary 1249 Exercises 1250 Chapter 35: Windows Communication Foundation 1252 What Is WCF ? 1253 WCF Concepts 1254 WCF Programming 1258 Summary 1282 Exercises 1283 Chapter 36: Windows Workflow Foundation 1284 Activities 1288 The Workflow Runtime 1303 Data Binding 1310 Summary 1315 Index 1316
LinqConnect is a fast and easy-to-use ORM solution, developed closely to the Microsoft LINQ to SQL technology, and supporting SQL Server, Oracle, MySQL, PostgreSQL, and SQLite. It provides a powerful model designer tool with complete integration to Visual Studio. Capability for customizing the default Type Mapping Rules is implemented Capability for setting diagram options either globally for all diagram documents or separately for a particular one is implemented: the Diagram Appearance and Printing options can now be set through the Options dialog box Capability for setting such options as Environment, Diagram and Servers' to adjust the Entity Developer behavior, Model diagram behavior and Type Mapping Rules to your needs is implemented Capability for setting and defining the class property validation rules based on different engines (Data Annotation, Enterprise Library, NHibernate Validator) is added The validation of method parameters is added The context menu options for unchecking changed/added/dropped tables are implemented for the root nodes in the "Update To/From Database" wizards The diagram design is changed: an arrow (instead of a triangle) is used on the tip of an association now The 'Numeric Primary Key As Identity' Oracle option is added: if this option is selected, the "StoreGeneratedPattern" will be set to Identity by default for Number primary keys The 'Integer Primary Key As Identity' SQLite option is added: if this option is selected, the "StoreGeneratedPattern" will be set to Identity by default for Integer primary keys The "Identifier Case Sensitive" check box, which enables case-sensitive processing of database object identifier names, is added to MySQL Server Options The documentation generation for Enum members is implemented The algorithm for forming the Navigation Properties names, when there are several FOREIGN KEY constraints between the same tables, is changed The documentation generation for navigation properties is implemented The "Recreate Model" option, allowing to rebuild the model from a scratch, is added to the "Update Model From Database" wizard The "GeneratePartialClass" template property to generate a partial class, which will not be overwritten by the designer, for each class in the model is added The behaviour is changed: the Navigation Property will not be displayed on the diagram and in Model Explorer if "Generate" is set to false for the appropriate association end The behaviour is changed: the Validate Max Length attribute is synchronized with the Max Length attribute of Property by default now The behaviour is changed: the Validate Required attribute is synchronized with the Nullable attribute of Property by default now The behaviour is changed: when selecting a property in the Model Explorer, the corresponding entity on the diagram does not expand if it is collapsed The behaviour is changed: the DATETIME2 data type is now used for columns, corresponding to System.DateTime properties, for Microsoft SQL Server 2008 and later The behaviour is changed: the 'Real' SQLite data type is now mapped to System.Double by default The behaviour is changed: database column comments are transfered to the Summary attribute of the Documentation property now The behaviour is changed: the TINYINT(1) data type is now used for the columns which correspond to the System.Boolean properties (MySQL)
Introduction This article present a tiny database engine which implements fixed width record tables and BTree indexes. This library is a work in progress, I am looking for some feedback on this to see if there is a need for it. This article is also a work in progress please bookmark and come back later, if you want to see the final article. Why an embedded database Although most of us will use a SQL Server to store and retrieve data sets. There are several situation where an embedded database make sense. When you don't have a SQL Server available When you want your footprint as small as possible and can't afford SQL Express When you want to manipulate or cache SQL data When you need to write highly procedural data manipulation routines When you want maximum speed Features Despite its small size DbfDotNet provides a number of features that you might find useful Type safe In DbfDotNet you manipulate classes with native field types. All data conversion plumbing is done automatically. Very simple entity framework Creating a record and accessing its propery is only what you need. Very small memory footprint Last time I checked the dbfDotNet dll was 50Kb. Other databases are 1Mb to 10Mb. I would appreciate if someone could do some memory usage comparison (I will insert it here). Fast DbfDotNet was conceived for speed. DbfDotNet do not use PInvoke, Threading locks, and do not implement any transaction system. Those 3 technologies have a performance cost that it won't have to pay. In contrast it is using TypeSafe records (without boxing/unboxing) and type safe emitted code. The code is emitted only once per table. It has therefore I believe the potential to be the fastest embedded .Net database there is. I would appreciate if someone could do some speed comparison (I will insert it here). Very small runtime memory usage When you use in Memory DataTable or SQL requests that return DataSets, the entire result sets is in memory. DbfDotNet works conjointly with the garbage collector. As soon as you're finished modifying an entity the garbage collector will mark the record buffer to be saved to disk and released from memory. Why Dbf By default the files are compatible with dBase and can therefore be open in Excel and many other packages. I have been asked : Why Dbf ? Dbf is an old format. The answer is a bit long but simple. As I said earlier DbfDotNet is designed to be as fast as possible. In order to get the database started and get some interest I need two things: A good product A good user base I know by experience that the DBF format will appeal to some of you for several reason: You can easily backup DBF files (and leave index files) You can check DBF content using Excel and many other tools DBF is well known and simple to implement It can be extended to modern types (and has been by clipper and fox pro) Most importantly for me, implementing the .DBF rather that my own custom format has no impact on runtime speed. How does it compare to ADO.Net, SQL, SqlLite, SharpSQL ... I did some speed test against another database (which I won't name) The results are quite encouraging. Dbf.Net ADO.Net Collapse Copy CodeOpening DbfDotNetDatabase: 185 ms Insert 1000 individuals: 39 ms Read individuals sequentially: 5 ms Read individual randomly: 3 ms Modifying individuals: 21 ms Create DateOfBirth index: 77 ms Michael Simmons 22/07/1909 Mark Adams 21/09/1909 Charles Edwards 28/09/1909 ... total 1000 records Enumerate Individuals by age: 36 ms Closing DbfDotNetDatabase: 44 ms Collapse Copy CodeOpening ADO.Net Database: 459 ms Insert 1000 individuals: 80601 ms Read individuals sequentially: 1655 ms Read individual randomly: 1666 ms Modifying individuals: 75574 ms Create DateOfBirth index: 80 ms Michael Simmons 22/07/1909 Mark Adams 21/09/1909 Charles Edwards 28/09/1909 ... total 1000 records Enumerate Individuals by age: 29 ms Closing ADO.Net Database: 0 ms In this test Dbf.Net runs nearly 400 times faster. This is quite unfair however. Dbf.Net does not have transactions and is not ACID. Lets not focus to much on speed but more on code differences: Creating a Table Creating the table is quite different. Dbf.Net requires a type safe record upfront to create a table. In ADO.Net you provide a string. Dbf.Net ADO.Net Collapse Copy CodeDbfTable mIndividuals; void CreateIndividualTable() { mIndividuals = new DbfTable( @"individuals.dbf", Encoding.ASCII, DbfDotNet.DbfVersion.dBaseIV); } class Individual : DbfDotNet.DbfRecord, IIndividual { [DbfDotNet.Column(Width = 20)] public string FIRSTNAME; [DbfDotNet.Column(Width = 20)] public string MIDDLENAME; [DbfDotNet.Column(Width = 20)] public string LASTNAME; public DateTime DOB; [DbfDotNet.Column(Width = 20)] public string STATE; } Collapse Copy CodeConnection _cnn = null; void ITestDatabase.CreateIndividualTable() { _cnn = new System.Data.Connection( "Data Source=adoNetTest.db"); _cnn.Open(); using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = "CREATE TABLE INDIVIDUAL (ID int primary key, FIRSTNAME VARCHAR(20), MIDDLENAME VARCHAR(20), LASTNAME VARCHAR(20), DOB DATE, STATE VARCHAR(20))"; cmd.ExecuteNonQuery(); } } Inserting new entries in a table: Dbf.Net ADO.Net Collapse Copy Codevoid InsertNewIndividual( int id, string firstname, string middlename, string lastname, DateTime dob, string state) { var indiv = mIndividuals.NewRecord(); indiv.FIRSTNAME = firstname; indiv.MIDDLENAME = middlename; indiv.LASTNAME = lastname; indiv.DOB = dob; indiv.STATE = state; indiv.SaveChanges(); } Collapse Copy Codevoid InsertNewIndividual( int id, string firstname, string middlename, string lastname, DateTime dob, string state) { using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = string.Format( "INSERT INTO INDIVIDUAL (ID, FIRSTNAME, MIDDLENAME, LASTNAME, DOB, STATE) VALUES({0}, '{1}', '{2}', '{3}', '{4}', '{5}');", id, firstname, middlename, lastname, dob.ToString("yyyy-MM-dd HH:mm:ss"), state); cmd.ExecuteNonQuery(); } } Getting an individual by record ID Dbf.Net ADO.Net Collapse Copy CodeIIndividual GetIndividualById(int id) { DbfDotNetIndividual result = mIndividuals.GetRecord(id); return result; } Collapse Copy CodeIIndividual GetIndividualById(int id) { using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = string.Format( "SELECT * FROM INDIVIDUAL WHERE ID=" + id); var reader = cmd.ExecuteReader(); try { if (reader.Read()) return GetNewIndividual(reader); else return null; } finally { reader.Close(); } } } Individual GetNewIndividual( DbDataReader reader) { var res = new Individual(); res.ID = reader.GetInt32(0); res.FirstName = reader.GetString(1); res.MiddleName = reader.GetString(2); res.LastName = reader.GetString(3); res.Dob = reader.GetDateTime(4); res.State = reader.GetString(5); return res; } class Individual : IIndividual { public int ID { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime Dob { get; set; } public string State { get; set; } } Saving a modified individual back to the database. In Dbf.Net you don't have to write any code, if you don't want to wait for the garbage collector to collect your individual you can call SaveChanges. Dbf.Net ADO.Net Collapse Copy Codevoid SaveIndividual( Individual individual) { individual.SaveChanges(); } Collapse Copy Codevoid SaveIndividual( IIndividual individual) { using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = string.Format( "UPDATE INDIVIDUAL SET DOB='{1}' WHERE ID={0};", individual.ID, individual.Dob.ToString( "yyyy-MM-dd HH:mm:ss")); cmd.ExecuteNonQuery(); } } Creating an Index Dbf.Net ADO.Net Collapse Copy Codevoid CreateDobIndex() { var sortOrder = new DbfDotNet.SortOrder( /*unique*/false); sortOrder.AddField("DOB"); mDobIndex = mIndividuals.GetIndex( "DOB.NDX", sortOrder); } Collapse Copy Codevoid CreateDobIndex() { using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = string.Format( "CREATE INDEX DOB_IDX ON INDIVIDUAL (DOB)"); cmd.ExecuteNonQuery(); } } Getting individuals sorted by Age Dbf.Net ADO.Net Collapse Copy CodeIEnumerable IndividualsByAge() { foreach (Individual indiv in mDobIndex) { yield return indiv; } } Collapse Copy CodeIEnumerable IndividualsByAge() { using (DbCommand cmd = _cnn.CreateCommand()) { cmd.CommandText = string.Format( "SELECT * FROM INDIVIDUAL ORDER BY DOB"); var reader = cmd.ExecuteReader(); try { while (reader.Read()) { yield return GetNewIndividual(reader); } } finally { reader.Close(); } } } High Level Interface I have been asked how I compare to other SQL databases. Again DbfDotNet is not a SQL engine. It is rather an object persistence framework, like the Microsoft Entity Framework or NHibernate. The difference is that it doesn't translate object manipulations into SQL requests because it speaks directly to the database layer. I would love to write a proper Dbf to Linq interface, if you want to help me on this please volunteer. The difference Using the code Warning: This project is at its infancy, it has not been tested thoroughly. You can try it but please don't use it in a live environment. If you want speed however and are ready to either report or fix issues that might arrise: Create a C# project Reference DbfDotNet.dll in your project Create a record class Write some code manipulate the records Point 3 and 4 are expanded below. The DbfRecord class The DbfRecord class represent one row in your table. You can can the column attribute to change DBF specific parameters. Collapse Copy Code class Individual : DbfDotNet.DbfRecord { [Column(Width = 20)] public string FIRSTNAME; [Column(Width = 20)] public string MIDDLENAME; [Column(Width = 20)] public string LASTNAME; public DateTime DOB; [Column(Width = 20)] public string STATE; }The system automatically chooses the DbfField most appropriate for your datatype. The DbfTable class In order to store your records somewhere you need to create a Table: Collapse Copy Code individuals = new DbfTable( @"individuals.dbf", Encoding.ASCII, DbfVersion.dBaseIV); Note that this using a type safe template. Every record in the table are individual's. Record Manipulation You can add new lines in the table by using the NewRecord Collapse Copy Code var newIndiv = individuals.NewRecord();Then you simply use the fields in your record Collapse Copy Code newIndiv.LASTNAME = "GANAYE";Optionally you can make a call to SaveChanges to immediately save your changes. If you don't the data will be saved when your individual is garbage collected. Collapse Copy Code newIndiv.SaveChanges(); Index support This is still very basic. First you define your sort order: Collapse Copy Code var sortOrder = new SortOrder(/* unique */ false); sortOrder.AddField("LASTNAME");Then you can get your index: Collapse Copy Code mIndex = individuals.GetIndex("lastname.ndx", sortOrder); You can then, In a type safe way, retrieve any individual from your index. Collapse Copy Code individual = mIndex.GetRecord(rowNo); In order to maximize speed, the index emit its own type safe code for : reading the index fields from the DBF record reading and writing index entries comparing index entries Inner architecture DbfDotNet main class is the ClusteredFile The ClusteredFile is a wrapper around stream that provide paging and caching support. The ClusteredFile is the base class for DbfFile and NdxFile. It will also be the base class for memo files when I write them. The ClusteredFile uses a class called QuickSerializer to serialize the record content to a byte array. QuickSerializer parse the Record fields and generate a bit of IL code for every fields to allow reading, saving and comparison. NdxFile implements a B+Tree index Roadmap My plan is to keep this library extremelly small. It is not my intention to implement any transaction or multi-threading support. I will implement : support for every DBF fields types memo fields (VARCHAR type) multiple indexes files (*.mdx) Proper documentation LINQ (in a separate dll) If you want to help me on this project please contact me. Points of Interest In order to maximize speed I forced myself to not use any thread synchronization locking. Each set of Dbf + Indexes must be called from a given thread. In other word each dbf file and its index can be used by only one thread. I encountered a problem though when the Garbage Collector finalize a record, this is done in the Garbage Collector thread. I did not want to lock a resource and ended up writing this code: Collapse Copy Codeclass Record { private RecordHolder mHolder; ~Record() { try { ... } finally { mHolder.RecordFinalized.Set(); } } } Each record has a RecordHolder that store a ReadBuffer and potentially a WriteBuffer. When the record finalize it signal the RecordHolder that the record has been finalized. This instruction is not blocking, it raises a flag that can be used in other threads. Collapse Copy Codeclass ClusteredFile { internal virtual protected Record InternalGetRecord(UInt32 recordNo) { RecordHolder holder = null; if (!mRecordsByRecordNo.TryGetValue(recordNo, out holder)) {...} record = holder.mRecordWeakRef.Target; if (record==null) { // the object is not accessible it has finalized a while ago or is being finalized if (holder.RecordFinalized.WaitOne()) { //Now it has finalized we will create a new record holder.RecordFinalized.Reset(); holder.Record = OnCreateNewRecord(/*isnew*/false, recordNo); } } return holder.Record; } } And then when the table thread try to get the record while it is disposing we use the method : holder.RecordFinalized.WaitOne() to make sure the finalization has completed first. Most of the time this method won't be blocking your DBF thread as the record has been finalized some time ago. History 2009 June 4th : Added samples and ADO.Net comparison 2009 June 1st : First DbfDotNet (C#) release. 2000 May 21st : I wrote my first database engine, it is called tDbf and works on Delphi. License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
2017年第二版, PDF格式 What this book covers Chapter 1, Hello, C#! Welcome, .NET Core!, is about setting up your development environment and using various tools to create the simplest application possible with C#. You will learn how to write and compile code using Visual Studio 2017 on Windows, or Visual Studio Code on macOS, Linux, or Windows. You will learn about the different .NET technologies: .NET Framework, .NET Core, .NET Standard, and .NET Native. Chapter 2, Speaking C#, is about the C# language---the grammar and vocabulary that you will use every day to write the source code for your applications. In particular, you will learn how to declare and work with variables of different types. Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, is about writing code that makes decisions, repeats a block of statements, converts between types, and handles errors. You will also learn the best places to look for help. Chapter 4, Using .NET Standard Types, is about commonly used .NET Core types that are part of .NET Standard and how they are related to C#. You will learn about the .NET Standard class library assemblies and the NuGet packages of types that allow your applications to connect existing components to perform common practical tasks, such as manipulating text, storing items in collections, and implementing internationalization. Chapter 5, Debugging, Monitoring, and Testing, is about debugging tools, monitoring, diagnosing problems, and testing your code to remove bugs and ensuring high performance, stability, and reliability. Chapter 6, Building Your Own Types with Object-Oriented Programming, is about all the different categories of members that a type can have, including fields to store data and methods to perform actions. You will use OOP concepts, such as aggregation and encapsulation. You will learn about the C# 7 language features such as tuple syntax support and out variables. Chapter 7, Implementing Interfaces and Inheriting Classes, is about deriving new types from existing ones using object-oriented programming (OOP). You will learn how to define operators and C# 7 local functions, delegates and events, how to implement interfaces about base and derived classes, how to override a type member, how to use polymorphism, how to create extension methods, and how to cast between classes in an inheritance hierarchy. Chapter 8, Working with Databases Using Entity Framework Core, is about reading and writing to databases, such as Microsoft SQL Server and SQLite, using the object-relational mapping technology known as the Entity Framework Core. Chapter 9, Querying and Manipulating Data with LINQ, is about Language INtegrated Query (LINQ)---language extensions that add the ability to work with sequences of items and filter, sort, and project them into different outputs. Chapter 10, Working with Files, Streams, and Serialization, is about managing the filesystem, reading and writing to files and streams, text encoding, and serialization. Chapter 11, Protecting Your Data, is about protecting your data from being viewed by malicious users using encryption and from being manipulated or corrupted using hashing and signing. Chapter 12, Improving Performance and Scalability with Multitasking, is about allowing multiple actions to occur at the same time to improve performance, scalability, and user productivity. Chapter 13, Building Universal Windows Platform Apps Using XAML, is about learning the basics of XAML that can be used to define the user interface for a graphical app for the Universal Windows Platform (UWP). This app can then run on Windows 10, Windows 10 Mobile, Xbox One, and even HoloLens. Chapter 14, Building Web Applications Using ASP.NET Core MVC, is about learning the basics of building web applications with a modern HTTP architecture on the server side using ASP.NET Core MVC. You will learn about the startup configuration, authentication, routes, models, views, and controllers that make up ASP.NET Core MVC. Chapter
一本不错的C#书,希望对您有帮助,本书目录: C# 3.0 Unleashed 1 Table of Contents 6 Introduction 30 Why This Book Is for You 31 Organization and Goals 32 Part 1 Learning C# Basics 36 1 Introducing the .NET Platform 38 What Is .NET? 38 The Common Language Runtime (CLR) 40 The .NET Framework Class Library (FCL) 43 C# and Other .NET Languages 45 The Common Type System (CTS) 46 The Common Language Specification (CLS) 46 Summary 46 2 Getting Started with C# and Visual Studio 2008 48 Writing a Simple C# Program 48 Creating a Visual Studio 2008 (VS2008) Project 52 Commenting Code 61 Identifiers and Keywords 64 Convention and Style 66 Variables and Types 67 Definite Assignment 73 Interacting with Programs 74 Summary 77 3 Writing C# Expressions and Statements 78 C# Operators 78 Statements 91 Blocks and Scope 92 Labels 92 Operator Precedence and Associativity 93 Selection and Looping Statements 94 Summary 106 4 Understanding Reference Types and Value Types 108 A Quick Introduction to Reference Types and Value Types 108 The Unified Type System 109 Reference Type and Value Type Memory Allocation 114 Reference Type and Value Type Assignment 117 More Differences Between Reference Types and Value Types 121 C# and .NET Framework Types 123 Nullable Types 131 Summary 132 5 Manipulating Strings 134 The C# String Type 134 The StringBuilder Class 151 Regular Expressions 153 Summary 158 6 Arrays and Enums 160 Arrays 160 The System.Array Class 166 Using Enum Types 168 The System.Enum struct 171 Summary 174 7 Debugging Applications with Visual Studio 2008 176 Stepping Through Code 176 Summary 188 Part 2 Object-Oriented Programming with C# 190 8 Designing Objects 192 Object Members 192 Instance and Static Members 193 Fields 194 Methods 195 Properties 196 Indexers 198 Reviewing Where Partial Types Fit In 199 Static Classes 200 The System.Object Class 201 Summary 204 9 Designing Object-Oriented Programs 206 Inheritance 207 Encapsulating Object Internals 213 Polymorphism 219 Summary 229 10 Coding Methods and Custom Operators 230 Methods 231 Overloading Methods 239 Overloading Operators 242 Conversions and Conversion Operator Overloads 247 Partial Methods 256 Extension Methods 257 Summary 259 11 Error and Exception Handling 260 Why Exception Handling? 261 Exception Handler Syntax: The Basic try/catch Block 261 Ensuring Resource Cleanup with finally Blocks 263 Handling Exceptions 264 Designing Your Own Exceptions 272 checked and unchecked Statements 274 Summary 277 12 Event-Based Programming with Delegates and Events 278 Exposing Delegates 279 Implementing Delegate Inference 285 Assigning Anonymous Methods 285 Coding Events 287 Summary 300 13 Naming and Organizing Types with Namespaces 302 Why Namespaces? 303 Namespace Directives 304 Creating Namespaces 307 Namespace Members 310 Scope and Visibility 311 Namespace Alias Qualifiers 312 Extern Namespaces Alias 313 Summary 315 14 Implementing Abstract Classes and Interfaces 316 Abstract Classes 317 Abstract Class and Interface Differences 319 Implementing Interfaces 320 Defining Interface Types 320 Implicit Implementation 322 Explicit Implementation 333 Interface Mapping 339 Interface Inheritance 341 Summary 344 Part 3 Applying Advanced C# Language Features 346 15 Managing Object Lifetime 348 Object Initialization 349 Object Initializers 355 Object Finalization 356 Automatic Memory Management 357 Proper Resource Cleanup 360 Interacting with the Garbage Collector 364 Summary 366 16 Declaring Attributes and Examining Code with Reflection 368 Using Attributes 369 Using Attribute Parameters 371 Attribute Targets 373 Creating Your Own Attributes 374 Using Reflection 378 Reflecting on Attributes 385 Summary 392 17 Parameterizing Type with Generics and Writing Iterators 394 Nongeneric Collections 395 Understanding the Benefits of Generics 395 Building Generic Types 401 Implementing Iterators 417 Summary 425 18 Using Lambda Expressions and Expression Trees 426 Lambda Expressions 427 Expression Trees 433 Summary 435 Part 4 Learning LINQ and .NET Data Access 436 19 Accessing Data with LINQ 438 LINQ to Objects 439 Querying Relational Data with LINQ to SQL 443 Standard Query Operators 456 Summary 468 20 Managing Data with ADO.NET 470 ADO.NET Architecture 470 Making Connections 474 Viewing Data 476 Manipulating Data 479 Calling Stored Procedures 481 Working with Disconnected Data 482 LINQ to DataSet 487 Summary 488 21 Manipulating XML Data 490 Streaming XML Data 491 Writing XML 491 Reading XML 494 Working with the XML DOM 495 Easier Manipulation with LINQ to XML 497 Summary 502 22 Creating Data Abstractions with the ADO.NET Entity Framework 504 An Overview of Entities 505 Starting the Entity Data Model in VS2008 505 Querying Entities with Entity SQL 509 Creating Custom Entities 511 Coding with LINQ to Entities 515 Summary 518 23 Working with Data in the Cloud with ADO.NET Data Services 520 Adding ADO.NET Data Services to Your Project 521 Accessing ADO.NET Data Services via HTTP URIs 522 Writing Code with the ADO.NET Data Services Client Library 528 Summary 533 Part 5 Building Desktop User Interfaces 534 24 Taking Console Applications to the Limit 536 Introducing the PasswordGenerator Console Application 537 Interacting with the User 537 Handling Command-Line Input 539 Adding Color and Positioning to Consoles 540 Summary 543 25 Writing Windows Forms Applications 544 Windows Forms Fundamentals 545 VS2008 Support for Windows Forms 548 Using Windows Forms Controls 557 MenuStrip, StatusStrip, and ToolStrip Controls 560 Data Grids and Data Binding 562 GDI+ Essentials 565 Additional Windows and Dialogs 568 Summary 574 26 Creating Windows Presentation Foundation (WPF) Applications 576 Just Enough XAML 577 Managing Layout 580 WPF Controls 589 Event Handling 602 Data Binding 603 Using Styles 607 Summary 609 Part 6 Designing Web User Interfaces 610 27 Building Web Applications with ASP.NET 612 The Web Application Model 612 Starting an ASP.NET Project with VS2008 615 A Lap Around an ASP.NET Page 617 Controls 622 State Management 625 Navigation 632 Theming a Site 638 Securing a Website 641 Data Binding 643 Summary 646 28 Adding Interactivity to Your Web Apps with ASP.NET AJAX 648 What Is AJAX? 648 Setting Up an ASP.NET AJAX Site 649 The AJAX Page Life Cycle 650 Loading Custom Script Libraries 652 ASP.NET AJAX Controls 654 Accessing Controls via JavaScript 657 Calling Web Services with ASP.NET AJAX 664 Summary 669 29 Crafting Rich Web Applications with Silverlight 670 What Makes Silverlight Tick? 670 Starting a Silverlight Project in VS2008 671 Handling Silverlight Events with C# 677 Playing Media 681 Animating UI Elements 684 Summary 686 Part 7 Communicating with .NET Technologies 688 30 Using .NET Network Communications Technologies 690 Implementing Sockets 690 Working with HTTP 698 Performing FTP File Transfers 700 Sending SMTP Mail 704 Summary 705 31 Building Windows Service Applications 708 Creating Windows Service Projects in VS2008 709 Coding Windows Services 712 Installing a Windows Service 717 Building a Controller to Communicate with a Windows Service 720 Summary 722 32 Remoting 724 Basic Remoting 724 Channels 735 Lifetime Management 738 Summary 741 33 Writing Traditional ASMX Web Services 742 Web Service Basics 742 Using Web Services 748 Summary 752 34 Creating Web and Services with WCF 754 Creating a WCF Application in VS2008 755 Creating a Web Service Contract 756 Implementing Web Service Logic 761 Configuring a Web Service 763 Consuming a Web Service 766 Summary 768 Part 8 Examining .NET Application Architecture and Design 770 35 Using the Visual Studio 2008 Class Designer 772 Visualizing Code 772 Building an Object Model with the Class Designer 778 Summary 783 36 Sampling Design Patterns in C# 784 Overview of Design Patterns 784 The Iterator Pattern 785 Implementing the Proxy Pattern 797 Implementing the Template Pattern 801 Summary 807 37 Building N-Tier/Layer Systems 808 Potential Drag-and-Drop Problems 808 Introducing N-Layer/N-Tier 810 N-Layer Architecture Examples 813 Summary 824 38 Automating Logic with Windows Workflow 826 Starting a Workflow Project 826 Building a Sequential Workflow 827 Building a State Workflow 832 Summary 842 Part 9 Surveying More of the .NET Framework Class Library 844 39 Managing Processes and Threads 846 .NET Process Support 847 Multithreading Overview 852 Thread Synchronization 855 Summary 858 40 Localizing and Globalization 860 Resource Files 860 Multiple Locales 872 Summary 880 41 Performing Interop (P/Invoke and COM) and Writing Unsafe Code 882 Unsafe Code 883 Platform Invoke 893 Communicating with COM from .NET 895 Exposing a .NET Component as a COM Component 898 Introduction to .NET Support for COM+ Services 900 Summary 905 42 Instrumenting Applications with System.Diagnostics Types 908 Simple Debugging 909 Conditional Debugging 910 Runtime Tracing 913 Making Assertions 915 Accessing Built-In Performance Counters 917 Implementing Timers 925 Building a Customized Performance Counter 926 Analyzing Performance with Sampling 937 Summary 946 Part 10 Deploying Code 948 43 Assemblies and Versioning 950 Inside Assemblies 950 Assembly Features 954 Configuration 956 Deployment 959 Summary 959 44 Securing Code 962 Code-Based Security 962 Role-Based Security 971 Security Utilities 973 Summary 974 45 Creating Visual Studio 2008 Setup Projects 976 Running the VS2008 Setup Project Wizard 976 Additional Setup Configuration 979 Summary 983 46 Deploying Desktop Applications 984 Deploying via ClickOnce 984 Configuring ClickOnce 986 Summary 988 47 Publishing Web Applications 990 The Anatomy of a Web Application 990 Web Server Setup 991 Virtual Directory Setup 992 Web Server Deployment 994 Publishing a Web App from VS2008 994 Summary 995 Part 11 Appendixes 996 A: Compiling Programs 998 Advanced 998 Assemblies 1000 B: Getting Help with the .NET Framework 1002 Read This Book 1002 Index 1003 .NET Framework Class Library Documentation 1003 Search Engines 1004 Favorite Websites 1004 Summary 1004

13,190

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 分析与设计
社区管理员
  • 分析与设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧