I'm trying to use Magical Record to import data into my CoreData db.
I'm working on the entity Person at the moment.
A Person has firstName, lastName, personID attributes. (I know I don't need the idString, I'm not using it internally, it is used to talk back to the server).
Anyway, if I already have the person...
firstName - John
lastName - Smith
personID - 1
And I download the JSON...
[
{
firstName: John,
lastName: Doe,
id: 1
},
{
firstName: Michael,
lastName: Caine,
id: 2
},
{
firstName: Angelina,
lastName: Jolie,
id: 3
}
]
I'd want the import to add Michael and Angelina and to update John Smith to John Doe because it already exists with the same id vs personID.
I've set the mappedKeyName between id and personID.
Is it possible to do this? I've been reading this blog... http://www.cimgf.com/2012/05/29/importing-data-made-easy/ about automatic mapping of key names etc... and wondered if I could exploit this to do what I want?
I have read the part about relatedByAttribute from the blog but I'm not sure where I should be setting it and what to?
Should I set it on the entity Person? Or the attribute personID? And what should I set it to? "id"? Or something else?
I'm not sure if you're using the relatedByAttribute setting in the userInfo area of your Core Data model. You don't mention that in your issue here. I suggest you double check that. And to clarify, it's called relatedByAttribute because the string you put into the value section is the CoreData attribute which relates the entities, no the json (or other object) data. So, check those two things and if there still a problem, please open a ticket on github, preferably with a unit test that helps describe the problem.
Related
I am trying to follow DDD for my current project. My question is specifically regarding POST request that contains values for my domain model. To simplify, let's say following is my domain model:
class Person
{
public int Id {get, set};
public string name {get, set};
}
And below is the entity model backing above domain:
class PersonEF
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get, set};
public string name {get, set};
}
Now when I receive a POST request to create a new Person it doesn't contain the Id as it's supposed to be generated by the database. I first map Person to PersonEF using AutoMapper which sets the Id to 0 in PersonEF and hence the INSERT in database fails. So to fix these my options are:
Name Id as something else in Person. If I do this then I would have to write custom mapping just for Id for GET requests.
Make Id nullable (int?) in both Person and PersonEF and this way auto increment will work, but having key as nullable int doesn't sound like a good idea in itself.
So please suggest the best way to do this.
EDIT
My bad. Code was missing context.SaveOrUpdate(). I added that and it's working as expected.
It's hard to say for sure, as the code of most importance, that you should have posted, would be that of your controller action where the mapping and saving occurs. However, I can tell you that the 0 is the default value for an int. This is not due to AutoMapper, or mapping in general, per se. The entity, freshly created, without any other interaction, would still have 0 as the id.
As a result, this should not be causing a problem with saving the entity, or else you'd never be able to save any entity that had an int PK. However, depending on what Entity Framework thinks you're trying to do with the entity, it might cause problems. Namely, you need to make sure that Entity Framework is aware that you're wanting to create this entity and not just update it. Usually, that's achieved by simply adding it to the DbSet:
db.PersonEFs.Add(personEF);
Not sure why you would need to go any farther than that, but if that's not working for some reason, you can be a bit more explicit:
db.Entry(personEF).State = EntityState.Added;
However, really, if you need to do that, there's something else going on that you'd just be masking.
sorry for this simple question. However, I am confused.
I want to read all Strings from the database.
Basically I am having a EmailSettings emailAddresses = new EmailSettings() object in my controller and want to read all emails saved in the emailSettings Domain object. The class looks like that:
class EmailSettings {
String emailAddress
static constraints = {
emailAddress(blank: false, nullable: false, email: true)
}
}
My problem is I do not get the saved email addresses out of the emailAddresses Object. I tried it with list(), getEmailAddress(like emailAddresses.getEmailAddress().toString(), which is null, even though in the db ARE email addresses saved under this domain object), but it does not work or I get an exception.
Any suggestion how to get the email addresses, which are saved in the db as an array?
I appreciate your answer!
You are creating a new domain instance by newifying it, which will never give you the results that is persisted in db. To get emailAddress from all EmailSettings in db, you can use as:
EmailSetting.all*.emailAdress
or
EmailSetting.withCriteria {
projections {
property 'emailAddress'
}
}
or can also use DetachedCriteria with above projection.
UPDATE
First approach will be expensive because all of the rows will be fetched and then emailAddress from each row will be derived. I totally missed mentioning why I had the second approach with usage of Criteria. Using Projections, you would only get the properties you would need instead of fetching the row itself. Thanks to Graeme.
I am using Grails 2.2.4 to build a web application, and now I am having a complex problem with Grails withCriteria operation. I have 3 classes as below:
class Person {
int id
String name
Set<Car> cars = [] // One-to-many relationship
Company currentCompany // One-to-one relationship
}
class Car {
int id
String manufacturer
String brand
double price
Person owner
}
class Company {
int id
String name
Set<Person> employees = []
}
And now I want to query data from Person as root class along with associated data like this:
List result = Person.withCriteria {
projections {
property('id')
property('name')
createAlias('cars', 'c', CriteriaSpecification.LEFT_JOIN)
property('c.brand')
createAlias('currentCompany', 'com', CriteriaSpecification.LEFT_JOIN)
property('com.name')
}
lt('id', 10L)
resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
}
And the problem is, I don't know how to transform deeply the result data to a List of persons to make sure every single element contains its data as the class structure. I tried many methods like
resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
resultTransformer(CriteriaSpecification.aliasToBean(Person.class))
but nothing worked as I expected.
Does Grails 2.2.4 support this? If yes so what is the correct syntax?
Thank you so much.
Actually, after researching many articles, Grails documentation and even its source code, I think the best way to do this is implementing a custom transformer for my own purpose. The most difficult thing here is how to transform data to association objects and gather them to collection inside the root entity. And I have created one here:
http://www.mycodestock.com/code/10333/
Hope it helps you guys who may need something like mine.
Groovy will all it's dynamic possibilities is still new to me and I'm kind of lost why below code does not work.
def luke = new FooPerson(firstName: "Luke", lastName: "Skywalker", initials: "LS", login: "luke", password: "luke" )
Above gives me proper values for firstName, lastName and initials and for login and password I get null.
If with above code I call
luke.setLogin("luke")
luke.setPassword("luke")
I will get proper value of all fields.
All five fields are declared in class
class Person {
static constraints = {
}
String firstName
String lastName
String initials
String login
String password
}
that my lovely FooPerson inherits from. My problematic fields were not initially in the Person class. I added them recently and obviously this causes groovy some stress.
Of course I can work around this, but I want to understand WHY it's working that weird way.
As noted by #dmahapatro upgrading to grails 2.2.4 solves the problem.
I've looked into release notes of Grails 2.2.4 and I don't see anything meaningful that could be connected to this, but it solves the problem.
Just using this as an example...
Here are the columns in my UserProfile table:
ProfileID (Primary key)
UserID (Foreign key)
Address
PhoneNumber
now, when I want to add a new user to the database using LINQ to Entities, here is what I'm doing:
UserProfile profileToAdd;
profileToAdd.ProfileID = 0;
profileToAdd.Address = "123 MyStreet";
profileToAdd.PhoneNumber = "123-4567";
/* How do I add in the UserID here? */
_myDB.AddToUserProfiles(profileToAdd);
A few questions...
Is there anything special about dealing with Foreign keys that I need to know, or can I assign it just as I did with Address or PhoneNumber?
The UserId is a Guid, and I need to retrieve it from the current user's UserId. I can't seem to get access to Membership class or User class (This is a C# Library so I'm guessing it needs a reference somehow, but my project is already referencing my Library so I can't reference back or I'll have a circular dependancy)
I don't quite understand how to deal with Guids. When implementing getProfileByUserName(string userName), here's my problem...
first off I can't retrieve the UserID, here's what I tried:
Guid currUser = (Guid)from user in _ myDB.aspnet_Users
where user.UserName == userName
select new { user.UserId };
But it says I can't cast it to a Guid for some reason.
If you can provide any insight to any of these questions I would greatly appreciate it!
Thanks,
Matt
If the database contains the proper constraints for the foreign key relationship, there should be a member in your UserProfile class, that points to a User object. The name might be a little weird, such as UserProfileUser or something like that.
However, you can change this name in the diagram. Just set a pointer to the user entity object and the framework will assign the correct id for you.