Форум программистов, компьютерный форум, киберфорум
C#: ASP.NET MVC
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.93/40: Рейтинг темы: голосов - 40, средняя оценка - 4.93
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
1

System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"

21.11.2019, 22:13. Показов 7880. Ответов 16
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый вечер, начал изучать ASP.NET MVC по мануалам в сети. Решил попробовать связку ASP.NET MVC + PostgreSQL но столкнулся с проблемой.
System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"


Web.config
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?xml version="1.0" encoding="utf-8"?>
<!--
  Дополнительные сведения о настройке приложения ASP.NET см. на странице
   https://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
          <add name="TestConnection" 
                   connectionString="Server=localhost;Database=Exam;User 
                   Id=postgres;
                   Password=1234;
                   port=5432" 
                   providerName="Npgsql" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="Forms">
      <forms name="auth" timeout="2880" loginUrl="~/Account/Login" />
    </authentication>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Devart.Data.PostgreSql" publicKeyToken="09af7300eec23701" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.15.1504.0" newVersion="7.15.1504.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <entityFramework>
    <providers>
      <provider invariantName="Npgsql"
                             type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
      </providers>
  </entityFramework>
      
        <system.data>
          <DbProviderFactories>
            <add name="Npgsql Data Provider" 
                     invariant="Npgsql" 
                     description="Data Provider for PostgreSQL"
                     type="Npgsql.NpgsqlFactory, Npgsql" 
                     support="FF" />
          </DbProviderFactories>
        </system.data>
</configuration>


User.cs
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace Exam.Models
{
    [Table("Users", Schema = "public")]
    public class User
    {
        [Key]
        //public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
    }
}


UserContext.cs
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace Exam.Models
{
    public class UserContext : DbContext
    {
        public UserContext() : base(nameOrConnectionString: "TestConnection")
        { }
 
        public DbSet<User> Users { get; set; }
 
    }
}


Models.cs
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace Exam.Models
{
    [Table("Users", Schema = "public")]
    public class LoginModel
    {
        [Key]
        public string Name { get; set; }
        public string Password { get; set; }
    }
    [Table("Users", Schema = "public")]
    public class RegisterModel
    {
        [Key]
        public string Name { get; set; }
        public string Password { get; set; }
    }
}


AccountController.cs
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using Exam.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Npgsql;
 
 
namespace Exam.Controllers
{
    public class AccountController : Controller
   {
        UserContext _context;
 
        public AccountController()
        {
            _context = new UserContext();
        }
        public ActionResult Login()
        {
            return View();
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                // поиск пользователя в бд
                User User = null;
                using (UserContext db = new UserContext())
                {
                    User = db.Users.FirstOrDefault(u => u.Name == model.Name && u.Password == model.Password);
 
                }
                if (User != null)
                {
                    FormsAuthentication.SetAuthCookie(model.Name, true);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }
            }
 
            return View(model);
        }
 
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User User = null;
                using (UserContext db = new UserContext())
                {
                    User = db.Users.FirstOrDefault(u => u.Name == model.Name);
                }
                if (User == null)
                {
                    // создаем нового пользователя
                    using (UserContext db = new UserContext())
                    {
                        db.Users.Add(new User { Name = model.Name, Password = model.Password });
                        db.SaveChanges();
 
                        User = db.Users.Where(u => u.Name == model.Name && u.Password == model.Password).FirstOrDefault();
                    }
                    // если пользователь удачно добавлен в бд
                    if (User != null)
                    {
                        FormsAuthentication.SetAuthCookie(model.Name, true);
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Пользователь с таким логином уже существует");
                }
            }
 
            return View(model);
        }
        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}


Помогите решить проблему новичку.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
21.11.2019, 22:13
Ответы с готовыми решениями:

Ошибка "Keyword not supported. Имя параметра: integrated security"
Всем привет, столкнулся с проблемой такого типа . Возникла она при добавление данных в БД....

Расширение модели User. "got not an unexpected keyword argument 'user'"
Здравствуйте, пытаюсь расширить дефолтную модель User следующим образом. class...

Исключение не обработано. System.ArgumentException: "Не удается найти столбец с именем КодКлиента. Имя параметра: column
В форме с подключенной через грид таблицей работает всё(поиск, добавление, выход, нормально...

При подключении БД phpmyadin на форму происходит ошибка "Keyword not supported: 'port'."
Код подключения БД using System; using System.Collections.Generic; using System.Text; using...

Подключение к БД. Ошибка "Keyword not supported: 'port'"
Подскажите пожалуйста, что не так!!! от код public DataSet GetUserTable() { string constr...

16
2755 / 2059 / 383
Регистрация: 22.07.2011
Сообщений: 7,780
22.11.2019, 15:59 2
Схему БД приложите.
Вряд-ли там ключем определено поле Name
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
22.11.2019, 16:40  [ТС] 3
System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"
0
2755 / 2059 / 383
Регистрация: 22.07.2011
Сообщений: 7,780
22.11.2019, 17:33 4
Vadimustus, а почему ваша модель Users не соответствует таблице в БД ?
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
22.11.2019, 17:59  [ТС] 5
Дописал
Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace Exam.Models
{
    [Table("Users", Schema = "public")]
    public class User
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public bool Role { get; set; }
    }
}

ошибка не ушла
0
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 18:54 6
deleted
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
22.11.2019, 19:12  [ТС] 7
IamRain что-что?
0
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 20:21 8
Vadimustus, ошибка все та же?

Добавлено через 4 минуты
Postgresql нечувствительно к регистру идентификаторов объектов, когда они не в кавычках. - Возможно поэтому провайдер postgresql генерит некорректный sql - запроc.
Добавьте атрибуты к вашим объектам, указывающие конкретно какое-имя столбца надо использовать.

Добавлено через 1 минуту
С SO:
This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).
Добавлено через 3 минуты
C#
1
2
3
4
5
6
7
8
9
[Table("Users", Schema = "public")]
    public class User
    {
        [Key, Column("ID")]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public bool Role { get; set; }
    }
Добавлено через 6 минут
Цитата Сообщение от Vadimustus Посмотреть сообщение
ошибка не ушла
Видимо EF по какой-то причине игнорирует атрибут и берет имя класса и добавляет к нему Id (convention) и затем все приводит к нижнему регистру, по идее должен быть userid, однако в postgres уходит user id (c пробелом). Если я правильно понял на основании того, что вы предоставили.
Column атрибут, как мне кажется, должен помочь.

Добавлено через 2 минуты
Пардон, атрибут, скорее всего, не игнорируется, но по какой-то причине добавляется пробел при формировании ключевого поля. Пробуйте с ColumnAttribute.

Добавлено через 10 минут
Проблема решилась?
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
22.11.2019, 20:29  [ТС] 9
IamRain, Ща попробую

Добавлено через 4 минуты
IamRain, К сожалению нет
0
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 20:49 10
Консолька. EFCore + Npgsql.
Вот такая строка подключения: "UserId=postgres;Password=<yourpassword>;Host=localhost;port=5432;Database=Users"

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Program
    {
        private static IConfigurationRoot ConfigurationRoot { get; set; }
 
        static void Main(string[] args)
        {
            ConfigurationRoot = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
 
            var conString = ConfigurationRoot.GetConnectionString("DefaultConnection");
 
            DbContextOptionsBuilder<UsersContext> builder = new DbContextOptionsBuilder<UsersContext>();
            builder.UseNpgsql(conString);
 
            using (var context = new UsersContext(builder.Options))
            {
                Console.Write("Ensure db created...");
                context.Database.EnsureCreated();
                Console.WriteLine("completed");
            }
            Console.WriteLine("Application run succeeded.");
            Console.ReadLine();
        }
    }
 
public class User
    {
        public int UserId { get; set; }
 
        public string Name { get; set; }
 
        public string LastName { get; set; }
 
        public string FirstName { get; set; }
 
        public string PasswordHash { get; set; }
    }
class UsersContext : DbContext
    {
        public UsersContext(DbContextOptions<UsersContext> contextOptions) : base(contextOptions)
        {
        }
 
        public DbSet<User> Users { get; set; }
    }
1
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 20:53 11
База создана. Добавлю запись в клиенте DBeaver и попробую получить из консольки.
Миниатюры
System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"  
1
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 21:12 12
Добавил метод получения записи (заведомо созданной с UserId =1).
C#
1
2
3
4
5
6
7
8
9
10
static void GetSomeUser(DbContextOptions<UsersContext> options)
        {
            using (var context = new UsersContext(options))
            {
                Console.Write("Getting orange cat data...");
                var user = context.Users.FirstOrDefault(x => x.UserId == 1);
                Console.WriteLine("completed");
                Console.WriteLine($"User data: {user?.ToString() ?? "Not found"}");
            }
        }
Код main-а:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
static void Main(string[] args)
        {
            ConfigurationRoot = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
 
            var conString = ConfigurationRoot.GetConnectionString("DefaultConnection");
 
            DbContextOptionsBuilder<UsersContext> builder = new DbContextOptionsBuilder<UsersContext>();
            builder.UseNpgsql(conString);
 
            using (var context = new UsersContext(builder.Options))
            {
                Console.Write("Ensure db created...");
                context.Database.EnsureCreated();
                Console.WriteLine("completed");
            }
 
            GetSomeUser(builder.Options);
 
            Console.WriteLine("Application run succeeded.");
            Console.ReadLine();
        }
Все создается, находится и отображается.
Миниатюры
System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"  
1
3635 / 2551 / 714
Регистрация: 02.08.2011
Сообщений: 6,889
22.11.2019, 21:12 13
Что-то вы делаете не так.
1
2755 / 2059 / 383
Регистрация: 22.07.2011
Сообщений: 7,780
23.11.2019, 00:01 14
Vadimustus, Можете stacktrace выложить ?
- будет понятно в какой внутренней функции ошибка
- видно , что это в System.Data , и видно , что ArgumentException - т.е при передаче аргумента в функцию , еще до того как БД выполнит скрипт.
- это может быть связано с конфигурацией в целом.

Добавлено через 4 минуты
Vadimustus,
а , госпади , так это тупо ошибка в конфиг файле )
ключевое слово для строки подключения неверное из-за переноса на новую строку

add name="TestConnection"
connectionString="Server=localhostatabase=Exam;User
Id=postgres;

Password=1234;
port=5432"
providerName="Npgsql" />
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
23.11.2019, 10:59  [ТС] 15
sau, нет, это не помогло, ошибка та же.
Кликните здесь для просмотра всего текста
Вызвано исключение: "System.Data.Entity.Core.ProviderIncompatibleException" в EntityFramework.dll
Исключение типа "System.Data.Entity.Core.ProviderIncompatibleException" возникло в EntityFramework.dll, но не было обработано в коде пользователя
An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.

Кликните здесь для просмотра всего текста
Exam.dll!Exam.Controllers.AccountController.Login(Exam.Models.LoginModel model)Строка 36
в D:\Exam\Exam\Controllers\AccountController.cs(36)


Добавлено через 38 минут
Соединения не было из-за ошибка в Web.config, а именно
C#
1
2
3
4
5
6
7
<connectionStrings>
<add name="TestConnection" 
                   connectionString="Server=localhost;Database=Exam;
                   User Id=postgres;
                   Password=1234;
                   port=5432" 
                   providerName="Npgsql" />
поменял на
C#
1
2
3
4
<connectionStrings>
<add name="Exam" providerName="Npgsql"
         connectionString="Server=127.0.0.1;User Id=postgres;Password=1234;Port=5432;Database=Exam;" />
  </connectionStrings>
Видимо из-за отсутсвия providerName="Npgsql" не могло соединиться с базой, осталась еще одна ошибка.
0
2755 / 2059 / 383
Регистрация: 22.07.2011
Сообщений: 7,780
23.11.2019, 11:40 16
Цитата Сообщение от Vadimustus Посмотреть сообщение
sau, нет, это не помогло, ошибка та же.
по тексту , это совершенно иная ошибка.
вообще , ошибок у Вас там туча может быть )
1
0 / 0 / 0
Регистрация: 27.02.2018
Сообщений: 35
23.11.2019, 12:01  [ТС] 17
sau, может и так, теперб я хоть вижу базу данных в обозревателе серверов)
вот следующая ошибка.
System.ArgumentException:"Keyword not supported:user id Имя параметра Keyword"

Забыл поменять имя соединения в UserContext.
Благодарю Вас за оказанную помощь!
0
23.11.2019, 12:01
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
23.11.2019, 12:01
Помогаю со студенческими работами здесь

Invalid use me of keyword
Тестирую программу, но не могу исправить ошибку, уже и забыл от части язык.. Может кто вразумит? ...

Ошибка: Invalid use of keyword
Invalid use of keyword. token 2.db where line number:2; В чем ошибка подскажите пожалуйста....

Ошибка: Invalid use of keyword
Invalid use of keyword. token FROM line number:1; В чем ошибка подскажите пожалуйста, Начинающий...

You are trying to create a MonoBehaviour using the 'new' keyword
Всем привет. Имеется: You are trying to create a MonoBehaviour using the 'new' keyword. This...

Keyword weight in Body
Программка при обнаружении плотности ключевых слов в тексте написала что значение должно...

Ошибка MonoBehaviour using the 'new' keyword
Выводит ошибку в Unity в чем проблема? В чем проблема Unity выводит следующюю оошибку You are...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
17
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru