C# Fixture OmitAutoProperties - c#

Is there any way to use OmitAutoProperties except entity.Id (Key) and only User.Id (ForeignKey)?
var user = new Fixture().Build<User>().Create();
var entity = new Fixture().Build<Game>().With(x => x.User, user).Create();

You can use With:
var fixture = new Fixture();
var user = fixture
.Build<User>()
.OmitAutoProperties()
.With(p => p.Id)
.Create();
var entity = fixture
.Build<Game>()
.OmitAutoProperties()
.With(p => p.Id)
.With(p => p.User, user)
.Create();

Related

Anonymous Object Breaking The Entire Method [duplicate]

This question already has an answer here:
How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1
(1 answer)
Closed 6 months ago.
This is my first time using an anonymous function with LINQ syntax. We are getting multiple Id's to set up a way for us to query another table for a specific "effective date" but something is throwing off my query.
Error Message
'((Microsoft.AspNetCore.Http.DefaultHttpContext)httpContext).Session' threw an exception of type 'System.InvalidOperationException'
"System.InvalidOperationException: The LINQ expression
'GroupByShaperExpression:\nKeySelector: new { \n operatorId =
t.OperatorId, \n regionId = t.RegionId\n },
\nElementSelector:new { \n operatorId =
ProjectionBindingExpression: operatorId, \n regionId =
ProjectionBindingExpression: regionId, \n effectiveDate =
ProjectionBindingExpression: effectiveDate\n }\n
.OrderByDescending(ed => ed.effectiveDate)' could not be
translated. Either rewrite the query in a form that can be
translated, or switch to client evaluation explicitly by
inserting
a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or
'ToListAsync'.
Any help would be great!
Query
var opRegionEffectiveDate = await (from reg in _orppr.GetAllQueryable()
.Where(opReg => result.Select(o => o.Id).Contains(opReg.OperatorId)).Select(opReg => new {operatorId = opReg.OperatorId, regionId = opReg.RegionId, effectiveDate = opReg.EffectiveDate}).Distinct()
group reg by new {reg.operatorId, reg.regionId}
into regef
select new { oprId = regef.Key.operatorId, regId = regef.Key.regionId, efdate = regef.OrderByDescending(ed => ed.effectiveDate).FirstOrDefault()})
.ToListAsync();
Full Method
public async Task<IEnumerable<OperatorViewModel>> GetAllAsync()
{
var retList = new List<OperatorViewModel>();
var result = await _operatorRepository.GetAllQueryable().Include(o => o.GroupEmails).Where(o => o.TenantId == TenantId).ToListAsync();
// var regions = _orppr.GetAllQueryable();
var opRegionEffectiveDate = await (from reg in _orppr.GetAllQueryable()
.Where(opReg => result.Select(o => o.Id).Contains(opReg.OperatorId)).Select(opReg => new {operatorId = opReg.OperatorId, regionId = opReg.RegionId, effectiveDate = opReg.EffectiveDate}).Distinct()
group reg by new {reg.operatorId, reg.regionId}
into regef
select new { oprId = regef.Key.operatorId, regId = regef.Key.regionId, efdate = regef.OrderByDescending(ed => ed.effectiveDate).FirstOrDefault()})
.ToListAsync();
var regions = await _regionRepository.GetAllQueryable()
.Where(reg => opRegionEffectiveDate.Select(ore => ore.regId).Contains(reg.Id))
.ToListAsync();
foreach (var oper in result)
{
var regionsToAdd = opRegionEffectiveDate.Where(r => r.oprId == oper.Id).Select(r => r.regId);
var regionsList = regions.Where(r => regionsToAdd.Contains(r.Id));
// var currRegions = await regions.Where(opReg => opReg.OperatorId == oper.Id)
// .Include(opReg => opReg.Region)
// .Select(opReg => opReg.Region)
// .OrderBy(reg => reg.Name)
// .Distinct()
// .ToListAsync();
var currOper = _mapper.Map<Operator, OperatorViewModel>(oper);
currOper.Regions = _mapper.Map<IEnumerable<Region>, IEnumerable<RegionViewModel>>(regionsList);
foreach(var reg in currOper.Regions)
{
var item = opRegionEffectiveDate.Single(r => r.oprId == oper.Id && r.regId == reg.Id);
reg.EffectiveDate = item.efdate.ToString();
}
retList.Add(currOper);
}
return retList.OrderBy(r => r.OperatorName);
}
Try following :
var opRegionEffectiveDate = await (_orppr
.GetAllQueryable().Where(opReg => result.Select(o => o.Id).Contains(opReg.OperatorId))
.OrderByDescending(ed => ed.effectiveDate)
.Select(opReg => new {operatorId = opReg.OperatorId, regionId = opReg.RegionId, effectiveDate = opReg.EffectiveDate})
.GroupBy(reg =>new {reg.operatorId, reg.regionId})
.Select(x => x).FirstOrDefault()
.Select(x => new { oprId = x.Key.operatorId, regId = x.Key.regionId, x.effectiveDate})
.ToListAsync()
);
var opRegionEffectiveDate = await _orppr
.GetAllQueryable().Where(opReg => result.Select(o => o.Id).Contains(opReg.OperatorId))
.Distinct()
.OrderByDescending(ed => ed.effectiveDate)
.Select(opReg => new {operatorId = opReg.OperatorId, regionId = opReg.RegionId, effectiveDate = opReg.EffectiveDate})
.GroupBy(reg =>new {reg.operatorId, reg.regionId})
.Select(x => x).FirstOrDefault()
.Select(x => new { oprId = x.operatorId, regId = x.regionId, x.effectiveDate})
.ToListAsync();

EF Core, use include or again context

Since:
"Eager loading a collection navigation in a single query may cause
performance issues."
see: Source
And it is advise to use split queries with include. I wonder if instead of include in the query bellow:
var task = await context.Tasks
.Include(x => x.TaskDependencies)
.Select(x => new TaskBaseModel
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
TaskDependencies= x.TaskDependencies.ToArray()
})
.SingleOrDefaultAsync(x => x.Id == _id);
I should do this:
var task = await context.Tasks
.Select(x => new TaskBaseModel
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
TaskDependencies= context.TaskDependencies
.Where(y => y.TaskId == x.Id).ToArray()
})
.SingleOrDefaultAsync(x => x.Id == _id);
Anyone as any info regarding this? about performance, etc..
Regards
Both queries should have the same performance and SQL. Note that Include followed by Select is ignored by EF Core.
So, most comfortable query is:
var task = await context.Tasks
.Select(x => new TaskBaseModel
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
TaskDependencies = x.TaskDependencies.ToArray()
})
.SingleOrDefaultAsync(x => x.Id == _id);

ElasticSearch.net Nest Match with Query doesnt work

I am using elasticsearch.net library to query ES. Facing issue related to finding results.Added screenshot which shows the results to my search used im query from Kibana.
When tried with below code No results are retrieved.
var searchResponse = client.Search<Product>(s => s
.Index("products1")
.From(0)
.Size(10)
.Query(q => q
.Match(m => m
.Field(f => f.Name)
.Query("Duracarb 32 oz (907.2 g)")
)
)
);
But when I tried with below code by adding match all able to retrieve 10 products successfully.
var searchResponse = client.Search<Product>(s => s
.Index("products1")
.From(0)
.Size(10)
.Query(q => q
.MatchAll()
)
);
Below is the full code I have used.
var uris = new[]
{
new Uri(_searchSettings.EnableElasticURL),
//new Uri("http://localhost:9201"),
//new Uri("http://localhost:9202"),
};
var connectionPool = new SniffingConnectionPool(uris);
var settings = new ConnectionSettings(connectionPool)
.DefaultIndex("products1");
var client = new ElasticClient(settings);
var searchRequest = new SearchRequest<Product>(Nest.Indices.All, Types.All)
{
From = 0,
Size = 10,
Query = new MatchQuery
{
Field = Infer.Field<Product>(f => f.Name),
Query = "Duracarb 32 oz(907.2 g)"
}
};
var searchResponse = client.Search<Product>(s => s
.Index("products1")
.From(0)
.Size(10)
.Query(q => q
.Match(m => m.Field(f => f.Name).Query("Duracarb 32 oz (907.2 g)")))
);
var stream = new System.IO.MemoryStream();
client.SourceSerializer.Serialize(searchResponse, stream);
var jsonQuery = System.Text.Encoding.UTF8.GetString(stream.ToArray());
var query = searchResponse.Documents;
var requestttt=searchResponse.DebugInformation;
//var query = GetProductQuery(searchQuery, null);
_logger.Debug("Search Response: "+query);
Change how field names are inferred from POCO property names:
var settings = new ConnectionSettings(connectionPool)
.DefaultFieldNameInferrer(n => n)
.DefaultIndex("products1");
Now, Infer.Field<Product>(f => f.Name) will serialize to "Name" to match the field name in the index mapping.
NEST by default camelcases POCO property names, so by default will serialize to "name".

Count files from request with Moq

The SetupGet for Form work, but the Count not work. How to resolve to Count return the value expected?
var httpContextMock = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
httpContextMock.SetupGet(x => x.Request).Returns(request.Object);
httpContextMock.SetupGet(x => x.Request.Form).Returns(form);
httpContextMock.SetupGet(x => x.Request.Files.Count).Returns(2);
It is not working because you are setting up the wrong mock. Apply the setup on the request mock.
var httpContextMock = new Mock<HttpContextBase>();
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(_ => _.Form).Returns(form);
requestMock.Setup(_ => _.Files.Count).Returns(2);
httpContextMock.Setup(_ => _.Request).Returns(requestMock.Object);
Just to prove the above works, I tested it like this
var context = httpContextMock.Object;
Assert.AreEqual(2, context.Request.Files.Count);
and it worked.
I did a quick test and it works if you access the request through the mock context.
[Test()]
public void Test()
{
var httpContextMock = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
httpContextMock.SetupGet(x => x.Request).Returns(request.Object);
httpContextMock.SetupGet(x => x.Request.Files.Count).Returns(2);
var count = httpContextMock.Object.Request.Files.Count;
Assert.AreEqual(2, count);
}
As Nkosi suggested, however, you probably wanted to setup Files.Count on the requestMock itself.

Rhino mocks of properties property

When I do these two lines after each other my code fails with Previous method 'HttpContextBase.get_Request();' requires a return value or an exception to throw. on the second line.
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
However when I do just one of the rows the code runs fine.
Doing the following does not fix the problem.
context.Expect(c => c.Request).Return(request);
Anyone understands this strange behaviour?
Thanks,
Drutten
Edit: Entire code is:
public static class Extensions
{
public static HttpContextBase FakeHttpContext()
{
var context = MockRepository.GenerateMock<HttpContextBase>();
var request = MockRepository.GenerateMock<HttpRequestBase>();
var response = MockRepository.GenerateMock<HttpResponseBase>();
var session = MockRepository.GenerateMock<HttpSessionStateBase>();
var server = MockRepository.GenerateMock<HttpServerUtilityBase>();
var writer = new StringWriter();
var form = new NameValueCollection();
request.Expect(r => r.Form).Return(form);
var uri = new Uri("http://localhost/IntegrationTests");
request.Expect(r => r.UrlReferrer).Return(uri).Repeat.Any();
var queryString = new NameValueCollection();
request.Expect(r => r.QueryString).Return(queryString);
context.Expect(c => c.Request).Return(request).Repeat.Any();
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
context.Expect(c => c.Response).Return(response);
context.Expect(c => c.Session).Return(session);
context.Expect(c => c.Server).Return(server);
context.Expect(c => c.Items).Return(new Dictionary<object, object>());
response.Expect(c => c.Output).Return(writer);
return context;
}
public static void MockControllerContext(this Controller controller)
{
var httpContext = FakeHttpContext();
var routeData = new RouteData();
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "Index");
controller.ControllerContext = new ControllerContext(new RequestContext(httpContext, routeData), controller);
}
}
I fixed the problem. The problem was probably related to the mix of
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
and
context.Expect(c => c.Request).Return(request).Repeat.Any();
Working code is:
var uri = new Uri("http://localhost/IntegrationTests");
request.Expect(r => r.UrlReferrer).Return(uri).Repeat.Any();
var queryString = new NameValueCollection();
request.Expect(r => r.QueryString).Return(queryString);
request.Expect(c => c.HttpMethod).Return("POST").Repeat.Any();
context.Expect(c => c.Request).Return(request).Repeat.Any();
I find it strange though that doing
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
once worked, even when not setting return on Request.

Categories

Resources