how to insert multiple values using entity framework..? - entity-framework

I'm using Silverlight5 with MVVM framework and Entity framework. In my project i have one doubt..
I have an entity named 'Customer' the structure is as follows..
Customer ocustomer = new Customer();
ocustomer.CustomerName = customername;
ocustomer.CompanyName = company;
ocustomer.AddressLine1 = address1;
ocustomer.AddressLine2 = address2;
ocustomer.City = city;
ocustomer.State = state;
ocustomer.Country = country;
ocustomer.ZipCode = zipcode;
ocustomer.Notes = note;
_context.Customers.Add(ocustomer);
Now my need is to insert the Customer value into another table Named Customer_Entity
Customer_Entity ocustomerEntity=new Customer_Entity ();
ocustomerEntity.CustomerID=Customer_ID;
ocustomerEntity.EntityTypeID =1;
.
.
.
.
ocustomerEntity.CreatedTime =System.DateTime.Now;
ocustomerEntity.CreatedBy=Common.ActiveData.Instance.userid;
Here my need is to insert the customer value to Customer_Entity in every single row..
Customer_Entity Table Structure is as follows,
EntityID| CustomerID| EntityValue|
----------------------------------
1 | 22 |jasper |
2 | 22 |Company:Raj |
3 | 22 |Address |
ocustomer.CustomerName=customername
.
.
.
ocustomer.CreatedTime=system.DateTime.Now..
so i need to insert all the values in every single row using unique CustomerID..
Need help to solve this one..

On your CustomerEntity object you should have a navigation property pointing to the corresponding Customer record. Similarly, I would expect that your Customer class has a collection of CustomerEntity on it as well.
In which case, you should instantiate the Customer object, populating with the necessary information. Don't add it to the DbSet yet, though. Afterwards, create all of the CustomerEntity records that you need to, connecting it to the Customer object by using the navigation property itself (i.e. NOT the ID field), and adding that CustomerEntity record to the corresponding DbSet in you Context class.
As a final step add your Customer object to the corresponding DbSet, and run SaveChanges. You should be good to go. Entity Framework should automatically generate the ID for you and populate it to the CustomerEntity records.

Related

Why can't EF handle two properties with same foreign key, but separate references/instances?

Apparently, EF6 doesn't like objects that have multiple foreign key properties that use the same key value, but do not share the same reference. For example:
var user1 = new AppUser { Id = 1 };
var user2 = new AppUser { Id = 1 };
var address = new Address
{
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
};
When I attempt to insert this record, EF throws this exception:
Saving or accepting changes failed because more than one entity of type
'AppUser' have the same primary key value. [blah blah blah]
I've discovered that doing this resolves the issue:
var user1 = new AppUser { Id = 1 };
var user2 = user1; //same reference
I could write some helper code to normalize the references, but I'd rather EF just know they're the same object based on the ID alone.
As for why EF does this, one explanation could be that its trying to avoid doing multipe CRUD operations on the same object since separate instances of the same entity could contain different data. I'd like to be able to tell EF not to worry about that.
Update
So it's as I suspected per my last paragraph above. In absense of a means to tell EF not to do CRUD on either instance, I will just do this for now:
if (address.ModifiedBy.Id == address.CreatedBy.Id)
{
address.ModifiedBy = address.CreatedBy;
}
Works well enough so long as I am not trying to do CRUD on either.
Update2
I've previously resorted to doing this to prevent EF from validating otherwise-required null properties when all I need is the child entity's ID. However, it doesn't keep EF from going into a tizzy over separate instances with the same ID. If it's not going to do CRUD on either AppUser object, why does it care if the instances are different?
foreach (var o in new object[] { address.ModifiedBy, address.CreatedBy })
{
db.Entry(o).State = EntityState.Unchanged;
}
If you get AppUser from context, then you will not need to do anything, because Entity Framework will track entities:
var user1 = context.AppUsers.Find(1);
var user2 = context.AppUsers.Find(1);
var address = new Address
{
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
};
Now, they both will point to same objects and will not cause to conflict.
You can add two extra properties to have the Id for the main objects which is the AppUser, then you can use only one AppUser object and reference it for both the created and modified by properties.
CreatedById = user1.Id,
ModifiedById = user1.Id
Otherwise, your code will end up by saving two instances of AppUser with the same primary key.
Another approach is to set both the foreign key properties to only one AppUserobject
The explanation is that EF's change tracker is an identity map. I.e. a record in the database is mapped to one, and only one, CLR object.
This can be demonstrated easily by trying to attach two objects with the same key:
context.AppUsers.Attach(new AppUser { Id = 1 });
context.AppUsers.Attach(new AppUser { Id = 1 });
The second line will throw an exception:
Attaching an entity of type 'AppUser' failed because another entity of the same type already has the same primary key value.
This also happens if you assign
CreatedBy = user1, //different reference
ModifiedBy = user2 //different reference
Somewhere in the process, user1 and user2 must be attached to the context, giving rise to the exception you get.
Apparently, you have a function that receives two Id values that can be different or identical. Admittedly, it would be very convenient if you could simply create two AppUser instances from these Ids, not having to worry about identical keys. Unfortunately, your solution ...
if (address.ModifiedBy.Id == address.CreatedBy.Id)
... is necessary. Solid enough, though.

JPA recursive entity StackOverflowError

I have a User entity generated in Netbeans from an existing database table. The table has a column lastUpdatedByUser that is a User entity. Most of the tables in this database have a lastUpdatedByUser column and queries against those entities correctly return a user object as part of the result.
Ex. Retrieve FROM ProductionTable WHERE date = 'someDate' has a lastUpdatedByUser object that shows who last updated the table row and the rest of their user attributes.
If the productionTable data is edited in the web-app and submitted I need to update the lastUpdatedByUser column.
Users userUpdating = usersService.selectUserEntityByUserId(userId);
Users userEntity = usersFacade.findSingleWithNamedQuery("Users.findByUserId", parameters);
SELECT u FROM Users u WHERE u.userId = :userId
returns a User object that contains a lastUpdatedByUser that is a User object that contains a lastUpdatedByUser that is a User object that contains a lastUpdatedByUser object.... (I have no clue how many there are, and twenty rows of these adds up)
After I persist this
productionEntity.setLastUpdatedByUser(userUpdating);
I get Json StackOverflowError in the next request for the updated entity
gson.toJson(updatedProductionEntity)
The Users entity definition:
#OneToMany(mappedBy = "lastUpdatedByUser")
private Collection<Users> usersCollection;
#JoinColumn(name = "LastUpdatedByUser", referencedColumnName = "UserId")
#ManyToOne
private Users lastUpdatedByUser;
#OneToMany(mappedBy = "lastUpdatedByUser")
private Collection<Production> productionCollection;
How can edit that such that I continue to get a user object as part of other entities like Production, but only a single lastUpdatedByUser object for a User entity?
Thanks for any insight.
I'm guessing this is my issue:
#JoinColumn(name = "LastUpdatedByUser", referencedColumnName = "UserId")
as I found a FK in the Users table to its own UserId
Love refactoring
================================
Drop that FK from the Users table and regenerate the entity in Netbeans and I get
private Integer lastUpdatedByUser;
like it should be
instead of
private Users lastUpdatedByUser;
Now I get to edit all the entities that have valid FKs into the Users table and code and...
Thanks for listening.

Get Record ID in Entity Framework 5 after insert

I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.
I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select ##IDENTITY as 'Identity';"
If anyone can help it would be greatly appreciated.
The default behavior of Entity Framework is it sets identity fields on entities from the database right after SaveChanges is called.
In the following sample code, before SaveChanges is called, my employee has a default ID of 0. After SaveChanges my employee has a generated ID of 1.
using (TestDbEntities context = new TestDbEntities())
{
Employee e = new Employee ();
e.FirstName = "John";
e.LastName = "Doe";
context.Employee.Add(e);
context.SaveChanges();
Console.WriteLine("Generated ID: {0}", e.ID);
Console.ReadKey();
}

Load Selected Primitive Properties in Entity Framework

I have following structure in Oracle database:
Course(CourseId, Name)
->Student(StudentId, Name, Comment, CourseId)
->Subject(SubjectId, Name, SubjectComment, CourseId)
Student contains some of Primitive Properties (StudentId, Name, CourseId, Comment) and Navigation Property (Courses [Linked with DTO name Course on CourseId]).
Table structure is also same as Entity structure and currenly using Explicit loading to extract the data from Oracle database, using LoadProperty and Load.
I need to load the Collection and Object with selected property, as Load Student with StudentId and Name (without Comment column).
LoadProperty(Student, s => s.Courses), load only CourseId (don't load Name primitive property in Course DTO). So, Student.Courses.First().CourseId will be a value and Name will be null as intentionally excluded from loading from database.
LoadProperty(Course, c => c.Subjects) load only SubjectId without Name property, even don't go to database to load.
Is there any way to Include/Exclude the Primitive types to load?
Not with load property and not with entities. You must create custom query and use projection to load only selected columns:
var student = from s in context.Students
select new {
StudentId = s.StudentId,
... // Other student's properties
CourseId = s.Course.Id,
SubjectIds = s.Courese.Subjects.Select(s => s.Ids)
};

Entity Framework - How to Set Association Value?

Let's say I have a Person class and an Order class, with foreign keys in the DB. The EF model will mark Person with a List of Orders and Order with a Person instance.
If I want to set the Person for the Order, do I really have to do it with an instance of Person?
Is there not a slimmed down way to do so, say with just a PersonID ?
To assign Person entity to a Order without loading Person entity, you have to do something like this:
var db = new OneToManyEntities();
var Order = new Order { OrderId = 100, OrderName = "Order name" };
Order. PersonReference.EntityKey = new EntityKey("OneToManyEntities.Person ","PersonID",10);
db.AddToOrders(Order);
db.SaveChanges();
Puzzled's answer is correct for EF v1. It's a pain. If you don't mind the extra query, you can set the property succinctly:
int id = 1;
Order.Person = context.Persons.Where(x => x.PersonID == id).FirstOrDefault();
Entity Framework v4 will have "FK Associations", which is a fancy term for directly-settable foreign keys.