Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace Pcf.GivingToCustomer.Core.Domain
{
public class BaseEntity
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid Id { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Collections.Generic;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;

namespace Pcf.GivingToCustomer.Core.Domain
{
Expand All @@ -7,13 +9,19 @@ public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }

public string FullName => $"{FirstName} {LastName}";

public string Email { get; set; }

// связь многие-ко-многим как лист ID
[BsonRepresentation(MongoDB.Bson.BsonType.String)]
public List<Guid> PreferenceIds { get; set; } = new List<Guid>();

[BsonRepresentation(MongoDB.Bson.BsonType.String)]
public List<Guid> PromoCodeIds { get; set; } = new List<Guid>();

[BsonIgnore]
public virtual ICollection<CustomerPreference> Preferences { get; set; }

[BsonIgnore]
public virtual ICollection<PromoCodeCustomer> PromoCodes { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="3.4.2" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using MongoDB.Driver;
using Pcf.GivingToCustomer.Core.Domain;
using System.Linq;

namespace Pcf.GivingToCustomer.DataAccess.Data
{
public class MongoDbInitializer : IDbInitializer
{
private readonly IMongoDBContext _context;

public MongoDbInitializer(IMongoDBContext context)
{
_context = context;
}

public void InitializeDb()
{
// чистим БД
_context.Database.DropCollection(nameof(Preference) + "s");
_context.Database.DropCollection(nameof(Customer) + "s");

// Добавляем Preferences
var preferencesCollection = _context.GetCollection<Preference>();
preferencesCollection.InsertMany(FakeDataFactory.Preferences);

// Добавляем Customers с вложенными Preferences
var customersCollection = _context.GetCollection<Customer>();
var customers = FakeDataFactory.Customers.Select(c =>
{
// В Mongo мы обычно не храним навигационные свойства,
// поэтому маппим Preferences -> список PreferenceIds
c.PreferenceIds = c.Preferences?.Select(p => p.PreferenceId).ToList();
c.Preferences = null; // навигационные свойства игнорируем
return c;
}).ToList();

customersCollection.InsertMany(customers);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using MongoDB.Driver;

namespace Pcf.GivingToCustomer.DataAccess
{
public interface IMongoDBContext
{
IMongoDatabase Database { get; }
IMongoCollection<T> GetCollection<T>(string name = null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using Pcf.GivingToCustomer.DataAccess.Settings;

namespace Pcf.GivingToCustomer.DataAccess
{
public class MongoDBContext : IMongoDBContext
{
private readonly IMongoDatabase _database;

public MongoDBContext(IOptions<MongoSettings> settings)
{
//клиент (один на приложение: singleton). Нужен для связи с сервером и работы с БД.
var client = new MongoClient(settings.Value.ConnectionString);
//по имени получаем БД
_database = client.GetDatabase(settings.Value.DatabaseName);
}

//короткая запись для свойства с геттером
public IMongoDatabase Database => _database;

public IMongoCollection<T> GetCollection<T>(string name = null)
{
var collectionName = name ?? typeof(T).Name + "s";
return _database.GetCollection<T>(collectionName);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
<PackageReference Include="MongoDB.Driver" Version="3.4.2" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using MongoDB.Driver;
using Pcf.GivingToCustomer.Core.Abstractions.Repositories;
using Pcf.GivingToCustomer.Core.Domain;
using Pcf.GivingToCustomer.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

public class MongoRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly IMongoCollection<T> _collection;

public MongoRepository(IMongoDBContext context)
{
_collection = context.GetCollection<T>();
}

public async Task<IEnumerable<T>> GetAllAsync()
{
return await _collection.Find(_ => true).ToListAsync();
}

public async Task<T> GetByIdAsync(Guid id)
{
var filter = Builders<T>.Filter.Eq(e => e.Id, id);
return await _collection.Find(filter).FirstOrDefaultAsync();
}

public async Task<IEnumerable<T>> GetRangeByIdsAsync(List<Guid> ids)
{
var filter = Builders<T>.Filter.In(e => e.Id, ids);
return await _collection.Find(filter).ToListAsync();
}

public async Task<T> GetFirstWhere(Expression<Func<T, bool>> predicate)
{
var filter = Builders<T>.Filter.Where(predicate);
return await _collection.Find(filter).FirstOrDefaultAsync();
}

public async Task<IEnumerable<T>> GetWhere(Expression<Func<T, bool>> predicate)
{
var filter = Builders<T>.Filter.Where(predicate);
return await _collection.Find(filter).ToListAsync();
}

public async Task AddAsync(T entity)
{
await _collection.InsertOneAsync(entity);
}

public async Task UpdateAsync(T entity)
{
var filter = Builders<T>.Filter.Eq(e => e.Id, entity.Id);
await _collection.ReplaceOneAsync(filter, entity);
}

public async Task DeleteAsync(T entity)
{
var filter = Builders<T>.Filter.Eq(e => e.Id, entity.Id);
await _collection.DeleteOneAsync(filter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Pcf.GivingToCustomer.DataAccess.Settings
{
public class MongoSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="MongoDB.Driver" Version="3.4.2" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="8.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="MongoDB.Driver" Version="3.4.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4" />
<PackageReference Include="NSwag.AspNetCore" Version="14.1.0" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Castle.Core.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Pcf.GivingToCustomer.Core.Abstractions.Gateways;
using Pcf.GivingToCustomer.Core.Abstractions.Repositories;
using Pcf.GivingToCustomer.DataAccess;
using Pcf.GivingToCustomer.DataAccess.Data;
using Pcf.GivingToCustomer.DataAccess.Repositories;
using Pcf.GivingToCustomer.DataAccess.Settings;
using Pcf.GivingToCustomer.Integration;

using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;

namespace Pcf.GivingToCustomer.WebHost
Expand All @@ -35,16 +28,26 @@ public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddMvcOptions(x=>
x.SuppressAsyncSuffixInActionNames = false);
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

// ���������� MongoDB
services.Configure<MongoSettings>(Configuration.GetSection("MongoSettings"));
// ������������ MongoContext
services.AddSingleton<IMongoDBContext, MongoDBContext>();
// ������������ �����������
services.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));
// ������� �������� �� FakeRepository
services.AddScoped<IDbInitializer, MongoDbInitializer>();

//services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddScoped<INotificationGateway, NotificationGateway>();
services.AddScoped<IDbInitializer, EfDbInitializer>();
services.AddDbContext<DataContext>(x =>
//services.AddScoped<IDbInitializer, EfDbInitializer>();
/*services.AddDbContext<DataContext>(x =>
{
//x.UseSqlite("Filename=PromocodeFactoryGivingToCustomerDb.sqlite");
x.UseNpgsql(Configuration.GetConnectionString("PromocodeFactoryGivingToCustomerDb"));
x.UseSnakeCaseNamingConvention();
x.UseLazyLoadingProxies();
});
});*/

services.AddOpenApiDocument(options =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings":{
"PromocodeFactoryGivingToCustomerDb":"Host=localhost;Database=promocode_factory_givingToCustomer_db;Username=postgres;Password=docker;Port=5435"
"ConnectionStrings": {
"PromocodeFactoryGivingToCustomerDb": "Host=localhost;Database=promocode_factory_givingToCustomer_db;Username=postgres;Password=docker;Port=5435"
},
"MongoSettings": {
"ConnectionString": "mongodb://admin:otus@localhost:27017",
"DatabaseName": "givingToCustomer"
},
"AllowedHosts": "*"
}