Расширение системы. Данные. Linq. DataContext

Аргументы командной строки передаются в первом параметре String[] в main(), например

public static void main( String[] args ) {
}

В приведенном выше примере args содержит все аргументы командной строки.

Короткий, приятный ответ на поставленный вопрос:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}
13
задан Kezzer 22 June 2009 в 10:57
поделиться

5 ответов

The object DataContext for linq does not have an empty constructor. Since it does not have an empty constructor you must pass one of the items it is excepting to the base.

From the MetaData for the DataContext.

// Summary:
//     Initializes a new instance of the System.Data.Linq.DataContext class by referencing
//     the connection used by the .NET Framework.
//
// Parameters:
//   connection:
//     The connection used by the .NET Framework.
public DataContext(IDbConnection connection);
//
// Summary:
//     Initializes a new instance of the System.Data.Linq.DataContext class by referencing
//     a file source.
//
// Parameters:
//   fileOrServerOrConnection:
//     This argument can be any one of the following: The name of a file where a
//     SQL Server Express database resides.  The name of a server where a database
//     is present. In this case the provider uses the default database for a user.
//      A complete connection string. LINQ to SQL just passes the string to the
//     provider without modification.
public DataContext(string fileOrServerOrConnection);
//
// Summary:
//     Initializes a new instance of the System.Data.Linq.DataContext class by referencing
//     a connection and a mapping source.
//
// Parameters:
//   connection:
//     The connection used by the .NET Framework.
//
//   mapping:
//     The System.Data.Linq.Mapping.MappingSource.
public DataContext(IDbConnection connection, MappingSource mapping);
//
// Summary:
//     Initializes a new instance of the System.Data.Linq.DataContext class by referencing
//     a file source and a mapping source.
//
// Parameters:
//   fileOrServerOrConnection:
//     This argument can be any one of the following: The name of a file where a
//     SQL Server Express database resides.  The name of a server where a database
//     is present. In this case the provider uses the default database for a user.
//      A complete connection string. LINQ to SQL just passes the string to the
//     provider without modification.
//
//   mapping:
//     The System.Data.Linq.Mapping.MappingSource.
public DataContext(string fileOrServerOrConnection, MappingSource mapping);

Something as simple as this would work. Any class that inherits from the DataConext must pass to the base constructor at least one of the types it is excepting.

public class SomeClass : System.Data.Linq.DataContext
{
    public SomeClass(string connectionString)
        :base(connectionString)
    {

    }
}
6
ответ дан 2 December 2019 в 00:32
поделиться

@Sander: I think you were on the right track. Instead of using a partial class and implementing the function for the sproc I instead followed this blog and used the *.designer.cs file for implementing it. Whilst I'm still experiencing problems with invalid type casting it did get rid of the original problem.

0
ответ дан 2 December 2019 в 00:32
поделиться

I'm assuming that the namespace and (data-context) type name are correct... double check that first.

It sounds to me like the codegen has failed, and so you only have your half of the data-context (not the half that the IDE is meant to provide). There is a known bug in LINQ-to-SQL where this can fail if (as in your case) the using declarations are above the namespace. No, I am not joking. Try changing the code:

namespace IntranetMvcAreas
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Reflection;
    using System.Text;
    using IntranetMvcAreas.Areas.Accounts.Models;
    // the rest of your code

Now go into the designer, tweak something (for example, change the name of a property and change it back again) and hit save (this forces the codegen). Now see if it works.

5
ответ дан 2 December 2019 в 00:32
поделиться

Ответ Дэвида Басараба правильный и должен быть отмечен как ответ.

Ваш класс не предоставляет никакого конструктора, поэтому предоставляется конструктор по умолчанию. Конструкторы по умолчанию для производных классов могут быть предоставлены только в том случае, если базовый класс имеет конструктор без параметров. Однако класс DataContext, который является вашим базовым классом в этом примере, не предоставляет конструктор без параметров. Это объясняет сообщение об ошибке, возвращенное вам компилятором.

Изменить :

Пример:

class A {
    public A(string s) {
    }
}

class B : A {
}

Попытка компиляции, которая возвращает ошибку в классе B:

'A' не содержит конструктора который принимает аргументы «0»

2
ответ дан 2 December 2019 в 00:32
поделиться

Поведение генератора в отношении конструкторов в некоторой степени контролируется свойствами соединения DBML. Если Application Settings имеет значение True и есть имя свойства settings, он сгенерирует конструктор, который считывает строку подключения из параметров приложения сборки. Если есть строка подключения, она сгенерирует конструктор с жестко заданной строкой подключения в файле .designer.cs. Если ни того, ни другого не будет, конструктор не будет сгенерирован без параметра строки подключения, и вы можете безопасно предоставить конструктор без параметров в частичном классе, не вызывая конфликта.

Эти изменения настроек не выдерживают цикла туда и обратно. схему из базы данных, но я просто удаляю настройки подключения из свойств после внесения изменений и перед сохранением DBML.

1
ответ дан 2 December 2019 в 00:32
поделиться
Другие вопросы по тегам:

Похожие вопросы: