Summary of problems and solutions in ASP. net mvc development and design [continuous update], asp. netmvc

Source: Internet
Author: User

Summary of problems and solutions in ASP. net mvc development and design [continuous update], asp. netmvc

ASP. net mvc 4.0 + linq to SQL is used TO develop and design multiple business system websites within the company. Some problems have been found here, and it takes a lot of time TO find relevant information or consult senior personnel, finally, all the problems are solved. Now I have summarized these problems and corresponding solutions for your reference. There are some mistakes or better solutions, welcome to comments in this article. Thank you!

[Released at 2014-12-2]

Problem 1: execute a similar statement: dbDataContext. tableName. join (modelList as List <object type>, t1 => t1.id, t2 => t2.id, (t1, t2) => new {attribute assignment}), error: you cannot use a local sequence in the LINQ to SQL Implementation of the query operator (except the Contains operator.

Cause analysis: The ing object of the data table cannot be associated with the query object of the C # self-owned collection object. You must make sure that the query and operation of the LINQ statement are the ing object of the data table or the C # self-owned collection object.

Solution: dbDataContext. tableName. join (dbDataContext. tableName2, t1 => t1.id, t2 => t2.id, (t1, t2) => new {attribute assignment}), or dbDataContext. tableName. asEnumerable (). join (modelList as List <object type>, t1 => t1.id, t2 => t2.id, (t1, t2) => new {attribute assignment }), however, the latter has performance problems, because AsEnumerable () will immediately perform the query action, load all the data in TableName to the local memory before association with the subsequent modelList.

 

Question 2:Execute similar statements:DbDataContext. TableName. Select (t => new data table ing object class {attribute assignment}), error: explicit entity type "XXXXXXXXX" cannot be constructed in the query ".

Cause Analysis: taken from the original saying on the network, "the version of LINQ to SQL before RTM has a Bug. If an entity is explicitly constructed in the query, in some cases, a series of identical objects are obtained. Unfortunately, I have only seen this Bug in the materials, but this Bug has been fixed in the RTM version of LINQ to SQL, which is actually bypassed. Directly throwing an exception is a way to "solve the problem", although this is actually removing a feature-No feature will naturally have bugs, just as if there is no header, there will be no headache."

Solution: 1. change Select (t => new data table ing object class {attribute assignment}) to direct return Anonymous class: Select (t => new {attribute assignment }), or re-define the object class, remove the features related to data table ing, that is: Select (t => new custom object class {attribute assignment}), 2. use the GetCommand method and the extension method ExecuteQuery <T> provided by DataContext in LINQ to SQL. The Code is as follows:

public static class DataContextExtensions{    public static List<T> ExecuteQuery<T>(this DataContext dataContext, IQueryable query)    {        DbCommand command = dataContext.GetCommand(query);        dataContext.OpenConnection();         using (DbDataReader reader = command.ExecuteReader())        {            return dataContext.Translate<T>(reader).ToList();        }    }     private static void OpenConnection(this DataContext dataContext)    {        if (dataContext.Connection.State == ConnectionState.Closed)        {            dataContext.Connection.Open();        }    }}

During execution, you can first query with LINQ and then execute the ExecuteQuery method, for example:

Var query = dbDataContext. TableName. Select (); var modelList = dbDataContext. ExecuteQuery <data table ing entity class> (query );

Question 3: Use ModelState. when AddModelError ("field name", "error message") is added, Html is used in the VIEW. the error sequence displayed by ValidationSummary (false) is not necessarily the same as that displayed by AddModelError, that is:

ModelState. addModelError ("field name 1", "Error Message 1"); ModelState. addModelError ("field name 9", "error message 2"); ModelState. addModelError ("field name 6", "error message 3"); ModelState. addModelError ("field name 3", "Error Message 4"); ModelState. addModelError ("field name 5", "error message 5 ");

It may be displayed (unordered or sorted by field names ):

Error Message 1 Error Message 4 error message 5 Error Message 3 error message 9

This will obviously affect the user experience. Therefore, we recommend that you use the following methods to display the error as normal. The principle is very simple, because if ModelState is used. addModelError is the same key. If this parameter is set to null, the value is in the ModelState of the key. add items under Errors, and since Errors is eventually stored as List type, the index order is determined.

ModelState. addModelError ("", "error message 1"); ModelState. addModelError ("", "error message 2"); ModelState. addModelError ("", "error message 3"); ModelState. addModelError ("", "Error Message 4"); ModelState. addModelError ("", "error message 5 ");

 

Question 4: When an anonymous object is passed as the Model data to the View and displayed, an error is returned: "object" does not contain the definition of "XXX.

Cause analysis: the default access modifier of the anonymous type isInternalWhich means they can only be accessed from the set of programs they define. Once you have exceeded the boundaries of the Assembly, it will be parsed as a common object, so it does not have the direct index attribute.

Solution: 1. Use the Tuple tuples static class, that is:

Controller:
Var result = dbDataContext. tableName. select (s => Tuple. create (parameter assignment); used in View: @ model IEnumerable <dynamic> foreach (var item in Model) {<tr> <td> @ item. item1 </td> <td> @ item. item2 </td> <td> @ item. item3 </td> <td> @ item. item4 </td> <td> @ item. item5 </td> </tr>}

2. You can also use the ExpandoObject class. This is a type in. NET 4.0: ExpandoObject. ExpandoObject is a type that allows you to dynamically add and delete members at will when you are running the program again.

 
Controller:
Public ActionResult UsingExpando () {dynamic viewModel = new ExpandoObject (); viewModel. testString = "This is a test string"; return View (viewModel);} used in View: <p> @ Model. testString </p>

 

 

 

 

If there are new problems in the future, they will continue to be updated, learned at work, summarized in learning, summarized in practice, and mastered after practice!



 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.