PIbd-33_Abazov_A.A._KOP_29/AbazovApp/AccountsDataBaseImplement/Models/Account.cs
2023-11-16 20:39:00 +04:00

110 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AccountsContracts.BindingModels;
using AccountsContracts.ViewModels;
using AccountsDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccountsDataBaseImplement.Models
{
public class Account : IAccountModel
{
[Required]
public string Login { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public string Email { get; set; } = string.Empty;
public int Id { get; private set; }
private Dictionary<int, IInterestModel>? _accountInterests = null;
[NotMapped]
public Dictionary<int, IInterestModel> AccountInterests
{
get
{
if (_accountInterests == null)
{
_accountInterests = Interests
.ToDictionary(recPI => recPI.InterestId, recPI => recPI.Interest as IInterestModel);
}
return _accountInterests;
}
}
[ForeignKey("AccountId")]
public virtual List<AccountInterest> Interests { get; set; } = new();
public static Account? Create(AccountBindingModel? model)
{
if (model == null)
{
return null;
}
return new Account()
{
Id = model.Id,
Login = model.Login,
Password = model.Password,
Email = model.Email,
};
}
public static Account? Create(AccountViewModel? model)
{
return new Account()
{
Id = model.Id,
Login = model.Login,
Password = model.Password,
Email = model.Email,
};
}
public void Update(AccountBindingModel? model)
{
if (model == null)
{
return;
}
Login = model.Login;
Password = model.Password;
}
public AccountViewModel GetViewModel => new()
{
Id = Id,
Login = Login,
Password = Password,
Email = Email,
};
public void UpdateInterests(AccountsDatabase context, AccountBindingModel model)
{
var accountInterests = context.AccountInterests.Where(rec => rec.AccountId == model.Id).ToList();
if (accountInterests != null && accountInterests.Count > 0)
{
// удалили те, которых нет в модели
context.AccountInterests.RemoveRange(accountInterests.Where(rec => !model.AccountInterests.ContainsKey(rec.InterestId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateInterest in accountInterests)
{
model.AccountInterests.Remove(updateInterest.InterestId);
}
var account = context.Accounts.First(x => x.Id == Id);
foreach (var pc in model.AccountInterests)
{
context.AccountInterests.Add(new AccountInterest
{
Account = account,
Interest = context.Interests.First(x => x.Id == pc.Key),
});
context.SaveChanges();
}
_accountInterests = null;
}
}
}
}