Файл не сопоставляется с помощью картографаC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Файл не сопоставляется с помощью картографа

Сообщение Anonymous »

У меня есть модель пользователя:

Код: Выделить всё

namespace Pharma.Models
{
public partial class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
public bool Active { get; set; }

public User()
{
if (FirstName == null)
{
FirstName = "";
}

if (Email == null)
{
Email = "";
}

}

}

}
и dto:

Код: Выделить всё

namespace Pharma.DTOs
{
public partial class UserForRegistrationDto
{
public string Email { get; set; }
public string Password { get; set; }
public string PasswordConfirm { get; set; }
public string FirstName { get; set; }

public UserForRegistrationDto()
{
if (Email == null)
{
Email = "";
}
if (Password == null)
{
Password = "";
}
if (PasswordConfirm == null)
{
PasswordConfirm = "";
}
if (FirstName == null)
{
FirstName = "";
}

}
}
}
а затем:

Код: Выделить всё

public class AuthController
{
private readonly AuthHelper _authHelper;
IAuthRepository _authRepository;
IUserRepository _userRepository;

IMapper _mapper;

public AuthController(IConfiguration config, IAuthRepository authRepository, IUserRepository userRepository)
{
_authHelper = new AuthHelper(config);
_authRepository = authRepository;
_userRepository = userRepository;
_mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.CreateMap();
}));

}

[HttpPost("Register")]
public async void RegisterAsync(UserForRegistrationDto userForRegistration)
{
byte[] passwordSalt = new byte[128 / 8];
// check if password and conformation are the same
if (userForRegistration.Password != userForRegistration.PasswordConfirm)
{
throw new Exception("Incorrect credentials!");
}
// check if user with same email already exists
if (await _authHelper.DoesUserExistByEmailAsync(userForRegistration.Email!))
{
throw new Exception("User already exists!");
}

_authHelper.GetPasswordHash(userForRegistration.Password, passwordSalt);
byte[] passwordHash = [];
byte[] passwordHashed = _authHelper.GetPasswordHash(userForRegistration.Password, passwordSalt);
string EmailForRegister = userForRegistration.Email;

List sqlParameters = new List();

SqlParameter passwordSaltParameter = new SqlParameter("@PasswordSalt", SqlDbType.VarBinary);
passwordSaltParameter.Value = passwordSalt;
SqlParameter passwordHashParameter = new SqlParameter("@PasswordHash", SqlDbType.VarBinary);
passwordHashParameter.Value = passwordHash;
sqlParameters.Add(passwordSaltParameter);
sqlParameters.Add(passwordHashParameter);
Console.WriteLine(sqlParameters);

UserToRegisterAuthDto userToRegisterAuthDto = new UserToRegisterAuthDto
{
Email = EmailForRegister,
passwordHash = passwordHashed,
passwordSalt = passwordSalt
};

_authRepository.AddEntity(userToRegisterAuthDto);

User userDb = _mapper.Map(userForRegistration);
_userRepository.AddEntity(userDb);
_userRepository.SaveChanges();
_authRepository.SaveChanges();

когда я хочу добавить в userDb базу данных, у меня нет имени; адрес электронной почты добавляется, но имя отсутствует, как будто оно не отображается; почему? И модель, и DTO имеют поле с именем FirstName и поэтому таблицу SQL (у нее есть поля UserId, FirstName, Email, Active). Я думал, что если поля имеют одно и то же имя, а в таблице SQL есть столбец с его именем , он будет работать без дополнительных настроек.
редактировать:

Код: Выделить всё

using Microsoft.EntityFrameworkCore;
using Pharma.Models;

namespace Pharma.Data
{
public class DataContextEF : DbContext
{
private readonly IConfiguration _config;

public DataContextEF(IConfiguration config)
{
_config = config;
}

public virtual DbSet Users { get; set; }
public virtual DbSet Substances { get; set; }
public virtual DbSet Dosages { get; set; }
public virtual DbSet
 Products { get; set; }

public virtual DbSet UsersAuth { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseSqlServer(_config.GetConnectionString("DefaultConnection"),
optionsBuilder => optionsBuilder.EnableRetryOnFailure());
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("dbo");

modelBuilder.Entity()
.ToTable("Users", "dbo")
.HasKey(u => u.UserId);

modelBuilder.Entity()
.ToTable("Substances", "dbo")
.HasKey(u => u.SubstanceId);

modelBuilder.Entity()
.ToTable("Dosages", "dbo")
.HasKey(u => u.DosageId);

modelBuilder.Entity()
.ToTable("Products", "dbo")
.HasKey(u => u.ProductId);

modelBuilder.Entity()
.ToTable("Auth2", "dbo")
.HasKey(u => u.Email);

}

}

}
я добавил контекст данных


Подробнее здесь: https://stackoverflow.com/questions/784 ... ing-mapper
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Файл не сопоставляется с помощью картографа
    Anonymous » » в форуме C#
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • ValidationException при сохранении в DynamoDB с помощью картографа
    Гость » » в форуме JAVA
    0 Ответы
    34 Просмотры
    Последнее сообщение Гость
  • StackOverflow: Exception_WasThrown с помощью специального картографа
    Гость » » в форуме C#
    0 Ответы
    48 Просмотры
    Последнее сообщение Гость
  • Как сериализовать поле карты как атрибуты xml с помощью картографа Джексона
    Anonymous » » в форуме JAVA
    0 Ответы
    21 Просмотры
    Последнее сообщение Anonymous
  • Свойство навигации не сопоставляется
    Anonymous » » в форуме C#
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»