This is the code in the Seed method:
var city = new City { Name = "A" };
var nh = new List<Neigh>
{
new Neigh { City = city, Name = "N1" },
new Neigh { City = city, Name = "N2" },
new Neigh { City = city, Name = "N3" },
//new Neigh { City = city, Name = "N4" },
};
context.Neighs.AddOrUpdate(
p => p.Name,
nh.ToArray()
);
After running update-database everything works as expected. I can run it multiple times without problem. However if at some point I uncomment the fourth neighborhood and run update-database again I end up with two records with city "A" and N4 is pointing to that city, while the rest point to the original city.
How do I prevent the inserting of a duplicate city if the list gets updated?
You must start the script by checking whether the city already exists:
var city = context.Cities.FirstOrDefault(c => c.Name == "A")
?? new City { Name = "A" };
Related
In my project I used to have more than 6.000 points of interest (pois). Now I need to access for example the title of one poi with specific ID. Normally it works fine in my app when I need some specific from user for example.
I do the same steps like I usually do. But when I try to access poi data, it only give the whole "poi" data (>6.000 pois). I tried getData even observeSingeEvent.
This is my database structure:
{
"pois" : {
"0015CF32-D5B2-481A-8DA2-877E621A4E82" : {
city = a,
"country" = a,
creator = System,
id = "0015CF32-D5B2-481A-8DA2-877E621A4E82",
latitude = "1",
longitude = "1",
street = "a",
title = "a",
type = 0,
zip = 1
}, + 6.000 more...
"users" : {
"6EA555FA-BAA8-4EDE-BD05-5D290B953CAC" : {
"City" : "Motown",
"Country" : "Anywhere",
"Forename" : "Fred",
"Surename" : "Feuerstein",
"onTour" : "false",
"registeredEmail" : "fred#feuerstein.com",
"userId" : "6EA555FA-BAA8-4EDE-BD05-5D290B953CAC",
"userImagePath" : "6EA555FA-BAA8-4EDE-BD05-5D290B953CAC.jpg",
"username" : "Tom"
}
}
}
My request and result for user data: (I reduced the whole code because it doesn't matter what happens within the completion)
database.child("users/6EA555FA-BAA8-4EDE-BD05-5D290B953CAC/registeredEmail").getData { error, snap in
print(snap)
}
results: Snap (registeredEmail) fred#feuerstein.com
My request and result for user data.
database.child("pois/42E11715-B3B0-46D9-A568-E578870EF9A4/title/").getData { error, snap in
print(snap)
}
results (Shorten):
Snap (title) {
"0015CF32-D5B2-481A-8DA2-877E621A4E82" = {
city = a;
"country" = a;
creator = System;
id = "0015CF32-D5B2-481A-8DA2-877E621A4E82";
latitude = "1";
longitude = "1";
street = "a";
title = "a";
type = 0;
zip = 1;
};
"002A3A1C-DE5C-4CB4-AD36-1B4495B77F22" = {
city = "b";
"country" = b;
creator = System;
id = "002A3A1C-DE5C-4CB4-AD36-1B4495B77F22";
latitude = "1";
longitude = "1";
rating = 0;
street = "b";
title = "b";
type = 0;
zip = 1;
}; + 6.000 more pois
I guess this coherent with the amount of data in "pois". Someone an idea how to solve the problem?
In my database I have last names and first names. I collect them in a array ; my variable lastAndFirstNameList contains: ex : [name, first name] => ( ["WOOD", "Robin"])
I then try to retrieve separately the last name and the first name with the variables lastname and firstname. I get the result « lastname undefined » and « firstname undefined ». I do not understand why! Could you help me please?
enter code here : //controller.js
Employee.getFirstAndLastName().$promise.then(function(result) {
var lastAndFirstNameList = result.list;
var lastname = lastAndFirstNameList.lastName;
var firstname = lastAndFirstNameList.firstName;
for(var k = 0; k < lastAndFirstNameList.length; k++)
{
console.log("lastname", lastname);
console.log("firstname", firstname);
}
console.log("lastAndFirstNameList", lastAndFirstNameList);
}
....
enter code here daoImpl.java
#SuppressWarnings("unchecked")
#Override
public List<Object> getFirstAndLastName() {
SQLQuery querySQL = sessionFactory.getCurrentSession().createSQLQuery("select last_name, first_name from employee");
List<Object> firstAndLastNameList = querySQL.list();
return firstAndLastNameList;
}
What does this give you? I don't think that 'firstname' and 'lastname' will give you anything because the are not referenced correctly.
Employee.getFirstAndLastName().$promise.then(function(result) {
var lastAndFirstNameList = result.list;
var lastname = lastAndFirstNameList.lastName;
var firstname = lastAndFirstNameList.firstName;
console.log("lastname ", lastname);
console.log("firstname ", firstname);
console.log("lastAndFirstNameList", lastAndFirstNameList);
}
Change the above reference variable to look like this:
var lastname = lastAndFirstNameList[0].lastName;
var firstname = lastAndFirstNameList[0].firstName;
That should give you the first value if passed correctly from the server.
Your loop should then look like this:
for(var k = 0; k < lastAndFirstNameList.length; k++){
console.log("lastname", lastAndFirstNameList[k].lastName);
console.log("firstname", firstname[k].firstName);
}
I'm trying to figure out how to seed one to many data elements in the seed method of Entity Framework.
context.AddressTypes.AddOrUpdate(
p => p.Name,
new AddressType { Name = "Original" },
new AddressType { Name = "Shipping" },
new AddressType { Name = "Billing" }
);
context.Addresses.AddOrUpdate(
a => a.Address1,
new Address { Address1 = "123 West Main",
City = "Hannibal",
Region = "MO",
PostalCode = "12345",
Country = "USA",
Type = new AddressType { Id=1 } }
);
How do I add one of the three address types to the address object I am seeding? If I do it the way I have shown it creates a new object in the AddressTypes table.
Our programming involves some Mock testing using In-Memory Data. Therefore, we implemented the following code that would first create In-Memory Data of Customer objects
// Let us create some in-memory data
// Create a list of Customer
List<Customer> listOfCustomers = new List<BlahBlahExample.Domain.Objects.Customer>()
{ new Customer { CustomerID = "1 ",Orders = new HashSet<Order>(), CustomerDemographics = new HashSet<CustomerDemographic>(), CompanyName = "Chicago Bulls", ContactName = "Michael Jordan", ContactTitle = "top basket ball player", Address = "332 testing lane", City = "Chicago", Region = "Illinois", PostalCode = "484894", Country = "USA", Phone = "3293993", Fax = "39393" },
new Customer { CustomerID = "2 ",Orders = new HashSet<Order>(),CustomerDemographics = new HashSet<CustomerDemographic>() , CompanyName = "Miami Heat", ContactName = "Lebron James", ContactTitle = "second best basket ball player", Address = "90 test street", City = "Miami", Region = "Florida", PostalCode = "4869394", Country = "USA", Phone = "3293213", Fax = "33393" },
new Customer { CustomerID = "3 ",Orders = new HashSet<Order>(),CustomerDemographics = new HashSet<CustomerDemographic>() , CompanyName = "Oklahoma City Thunder", ContactName = "Kevin Durant", ContactTitle = "current top basket ball player", Address = "35 test row", City = "Oklahoma City", Region = "Oklahoma", PostalCode = "480290", Country = "USA", Phone = "304923", Fax = "33325" }
};
// Convert the list to an IQueryable list
IQueryable<Customer> queryableListOfCustomerInMemoryData = listOfCustomers.AsQueryable();
// Let us create a Mocked DbSet object.
Mock<DbSet<BlahBlahExample.Domain.Objects.Customer>> mockDbSet = new Mock<DbSet<BlahBlahExample.Domain.Objects.Customer>>();
// Force DbSet to return the IQueryable members
// of our converted list object as its
// data source
mockDbSet.As<IQueryable<BlahBlahExample.Domain.Objects.Customer>>().Setup(m => m.Provider).Returns(queryableListOfCustomerInMemoryData.Provider);
mockDbSet.As<IQueryable<BlahBlahExample.Domain.Objects.Customer>>().Setup(m => m.Expression).Returns(queryableListOfCustomerInMemoryData.Expression);
mockDbSet.As<IQueryable<BlahBlahExample.Domain.Objects.Customer>>().Setup(m => m.ElementType).Returns(queryableListOfCustomerInMemoryData.ElementType);
mockDbSet.As<IQueryable<BlahBlahExample.Domain.Objects.Customer>>().Setup(m => m.GetEnumerator()).Returns(queryableListOfCustomerInMemoryData.GetEnumerator());
mockDbSet.Setup(m => m.Add(It.IsAny<Customer>())).Callback<Customer>(listOfCustomers.Add);
Mock<BlahBlahAuditMappingProvider> jsAudtMppngPrvdr = new Mock<BlahBlahAuditMappingProvider>();
Mock<BlahBlahDataContext> fctry = new Mock<BlahBlahDataContext>(jsAudtMppngPrvdr.Object);
Mock<BlahBlahDataContext> qryCtxt = new Mock<BlahBlahDataContext>();
Mock<BlahBlahAuditContext> audtCtxt = new Mock<BlahBlahAuditContext>();
Mock<BlahBlahDataContext> mockedReptryCtxt = new Mock<BlahBlahDataContext>();
mockedReptryCtxt.Setup(q => q.Customers).Returns(mockDbSet.Object);
mockedReptryCtxt.Setup(q => q.Set<Customer>()).Returns(mockDbSet.Object);
mockedReptryCtxt.CallBase = true;
DbSet<Customer> inMemoryDbSetCustomer = mockedReptryCtxt.Object.Set<Customer>();
In the next excerpt of code( which is our "Code Under Test"), I add a new Customer to the existing In-Memory Data, and then Invoke SaveChanges on the Mocked Object.
Customer returnCust = (Customer)(mockedReptryCtxt.Object.Set<Customer>().Add(new Customer { CustomerID = "4 ", Orders = new HashSet<Order>(), CustomerDemographics = new HashSet<CustomerDemographic>(), CompanyName = "Kolkota Knights", ContactName = "Sachin Tendulkar", ContactTitle = "current top cricket player", Address = "35 test row", City = "Kolkota", Region = "West Bengal", PostalCode = "3454534", Country = "India", Phone = "304923", Fax = "33325" }));
mockedReptryCtxt.Object.SaveChanges();
Later on in the code, I have the following excerpt of code where _context.Set() will return the In-Memory Data DBSet that we created previously
var query = _context.Set<TEntity>().AsQueryable();
if (typeof(TEntity).Name.Contains("Audit"))
{
return query;
}
if (includes != null && includes.Any())
{
foreach (var include in includes)
{
query = query.Include(include);
}
}
List<TEntity> resultsAsList = query.ToList(); // Error Thrown When using ToList()
var results = resultsAsList.AsQueryable();
When we invoke ToList(), it Throws the following Error:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Collection was modified; enumeration operation may not execute.
Source=mscorlib
StackTrace:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at BlahBlah.Framework.EntityFramework.EntityFrameworkRepository`1.ConcreteQuery(List`1 includes) in d:\EMIS\BlahBlah Framework\BlahBlahFrameworkLightweight\BlahBlah.Framework.EntityFramework\EntityFrameworkRepository.c s:line 51
at Castle.Proxies.EntityFrameworkRepository`1Proxy.ConcreteQuery_callback(List`1 includes)
at Castle.Proxies.Invocations.EntityFrameworkRepository`1_ConcreteQuery.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Moq.Proxy.CastleProxyFactory.CallContext.InvokeBase()
at Moq.InvokeBase.HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.EntityFrameworkRepository`1Proxy.ConcreteQuery(List`1 includes)
at BlahBlah.Framework.Core.Repository.BaseRepository`1.Query(List`1 includes) in d:\EMIS\BlahBlah Framework\BlahBlahFrameworkLightweight\BlahBlah.Framework.Core\Repository\BaseRepository.cs:line 149
at Castle.Proxies.EntityFrameworkRepository`1Proxy.Query_callback(List`1 includes)
at Castle.Proxies.Invocations.IRepository`1_Query.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Moq.Proxy.CastleProxyFactory.CallContext.InvokeBase()
at Moq.InvokeBase.HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.EntityFrameworkRepository`1Proxy.Query(List`1 includes)
at BlahBlah.Test.Unit.CntrlrsTests.CustomerControllerTest.Test_Creation_Of_Customer_Using_Constructor_Of _Customer_Controller_That_Expects_Arguments() in d:\EMIS\BlahBlah Framework\BlahBlahFrameworkLightweight\BlahBlah.Test.Unit\CntrlrsTests\CustomerControllerTest.cs:line 278
InnerException:
What steps do we need to take in order to stop the said error from being thrown( preferably without Changing too much of our Code Under Test)?
I had this problem as well but not iterating over the collection isn't really an option for me. After some thought, I did figure out a solution. The issue is that the mock sets up the various IQueryable properties off of a fixed IQueryable object from the original list. That causes any modification of that list to invalidate the corresponding IQueryable. The solution is to get a new IQueryable on each access using a lambda with Moq.
Here's the helper function I created to make mocking out DBSets easier, using the described technique.
public static Mock<DbSet<T>> MockDbSet<T>(List<T> list) where T : class
{
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(() => list.AsQueryable().Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(() => list.AsQueryable().Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(() => list.AsQueryable().ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => list.GetEnumerator());
mockSet.Setup(m => m.Add(It.IsAny<T>())).Callback((T x) => list.Add(x));
mockSet.Setup(m => m.AddRange(It.IsAny<IEnumerable<T>>())).Callback((IEnumerable<T> x) => list.AddRange(x));
mockSet.Setup(m => m.Remove(It.IsAny<T>())).Callback((T x) => list.Remove(x));
mockSet.Setup(m => m.RemoveRange(It.IsAny<IEnumerable<T>>())).Callback((IEnumerable<T> x) => list.RemoveAll(x.Contains));
return mockSet;
}
Edit: Added AddRange, Remove, RemoveRange since why not...
Edit 2: Correction for RemoveRange
I found a really Clumsy Solution:
List<TEntity> tempList = new List<TEntity>();
for (int i = query.Count() - 1; i >= 0; i--)
{
tempList.Add(query.ElementAt(i));
}
List<TEntity> resultsAsList = tempList.ToList();
var results = resultsAsList.AsQueryable();
In the aforementioned code, it is important to use a for loop with an index to go through the DBSet instance. Furthermore, in the loop, you add each element to a List. ( Basically, it's important to Avoid using the Iterator)
Our programming involves some Mock testing using In Memory Data.
// Let us create some in-memory data
// Create a list of Customer
List<Customer> listOfCustomers = new List<BlahProjectBlahExample.Domain.Objects.Customer>()
{ new Customer { CustomerID = "1 ", CompanyName = "Chicago Bulls", ContactName = "Michael Jordan", ContactTitle = "top basket ball player", Address = "332 testing lane", City = "Chicago", Region = "Illinois", PostalCode = "484894", Country = "USA", Phone = "3293993", Fax = "39393" },
new Customer { CustomerID = "2 ", CompanyName = "Miami Heat", ContactName = "Lebron James", ContactTitle = "second best basket ball player", Address = "90 test street", City = "Miami", Region = "Florida", PostalCode = "4869394", Country = "USA", Phone = "3293213", Fax = "33393" },
new Customer { CustomerID = "3 ", CompanyName = "Oklahoma City Thunder", ContactName = "Kevin Durant", ContactTitle = "current top basket ball player", Address = "35 test row", City = "Oklahoma City", Region = "Oklahoma", PostalCode = "480290", Country = "USA", Phone = "304923", Fax = "33325" }
};
// Convert the list to an IQueryable list
IQueryable<Customer> queryableListOfCustomerInMemoryData = listOfCustomers.AsQueryable();
// Let us create a Mocked DbSet object.
Mock<DbSet<BlahProjectBlahExample.Domain.Objects.Customer>> mockDbSet = new Mock<DbSet<BlahProjectBlahExample.Domain.Objects.Customer>>();
// Force DbSet to return the IQueryable members
// of our converted list object as its
// data source
mockDbSet.As<IQueryable<BlahProjectBlahExample.Domain.Objects.Customer>>().Setup(m => m.Provider).Returns(queryableListOfCustomerInMemoryData.Provider);
mockDbSet.As<IQueryable<BlahProjectBlahExample.Domain.Objects.Customer>>().Setup(m => m.Expression).Returns(queryableListOfCustomerInMemoryData.Expression);
mockDbSet.As<IQueryable<BlahProjectBlahExample.Domain.Objects.Customer>>().Setup(m => m.ElementType).Returns(queryableListOfCustomerInMemoryData.ElementType);
mockDbSet.As<IQueryable<BlahProjectBlahExample.Domain.Objects.Customer>>().Setup(m => m.GetEnumerator()).Returns(queryableListOfCustomerInMemoryData.GetEnumerator());
Mock<BlahProjectBlahDataContext> mockedReptryCtxt = new Mock<BlahProjectBlahDataContext>();
mockedReptryCtxt.Setup(q => q.Customers).Returns(mockDbSet.Object);
mockedReptryCtxt.Setup(q => q.Set<Customer>()).Returns(mockDbSet.Object);
mockedReptryCtxt.CallBase = true;
DbSet<Customer> inMemoryDbSetCustomer = mockedReptryCtxt.Object.Set<Customer>();
In the following code, I used a loop to see the contents of the inMemoryDbSetCustomer, and it contained the expected data.
Customer something;
foreach (var entry in inMemoryDbSetCustomer)
{
something = entry as Customer;
}
Sadly, when I try to add a new customer,
1) the inMemoryDbSetCustomer fails to add the customer
2) the inMemoryDbSetCustomer.Add(someCust) returns NULL
3) the inMemoryDbSetCustomer seems to have lost all it's other Customer entries.
Customer someCust = new Customer { CustomerID = "4 ", CompanyName = "Kolkota Knights", ContactName = "Sachin Tendulkar", ContactTitle = "current top cricket player", Address = "35 test row", City = "Kolkota", Region = "West Bengal", PostalCode = "3454534", Country = "India", Phone = "304923", Fax = "33325" };
try
{
Customer returnCust = (Customer)(inMemoryDbSetCustomer.Add(someCust));
}
catch(Exception ex ){
}
Why is the DBSet Add failing, and also destroying the existing Customer entries in the DBSet?
Update With Answer
Thanks to #Werlang suggestion. The following code addition helped:
mockDbSet.Setup(m => m.Add(It.IsAny<Customer>()))
.Callback<Customer>((Customer c) => { listOfCustomers.Add(c); })
.Returns((Customer c) => c);
Also, if you mocking DBSets with Moq Framework like I am then the following stackoverflow posting will be helpful because you might face a similar problem:
What steps to get rid of Collection was modified; enumeration operation may not execute. Error?
You've mocked the queryable to return a fixed set of data, when accessed via IQueryable. But Add's are maintained in a separated list on DbContext internal in the form of DbEntry's.
I suggest you to mock the Add() method too, addind the new element to mocked array (listOfCustomers).