Entity Framework: referencing entities from a model of another context - entity-framework

I have two Db contexts: CustomersDb which maps to a Customers database, and OrdersDb, which maps to Orders database.
I have a model for each context
Customer
{
Id,
Name
}
Order
{
Id,
Virtual Customer
}
How how do I reference the Customer entity from the Orders model correctly? When I seed these DBs, EF creates a Customers table in the Orders database, and obviously, I don't want that

Related

Can I lazy load a navigation property by delegating to a stored procedure in EF?

I have the following customer class:
public class Customer
{
public long Id { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
My database has Customers and Orders tables, but no foreign key relationships. Orders for a customer are obtained using a stored procedure that takes the customer ID and returns the order rows. I can't modify the database.
I know how to call the stored procedure from Entity Framework, but, is it possible to configure the DbContext using the fluent API so that accessing the Orders collection of a customer object would lazy load the entities via a call to the stored procedure?
I'm using the latest version of EF.
No, you can't. Lazy loading is coded in the proxy object that EF creates (if possible), there's no way to intercept/configure the way proxies are generated.
It's not even possible to map the default read action of a DbSet to a stored procedure. It's always a query. Only create, update and delete can be mapped to stored procedures.
The reason (I think) is that stored procedures are not composable, so if in a complex LINQ query one entity would be mapped to a stored procedure (for reading) it wouldn't be possible to turn the query into one SQL statement.

How to clear many to many relationship without loading from database in EF?

I have the following entities (pocos using Entity Framework 5):
Company: Id, Name, Applications, etc.
Application: Id, Name, etc.
There's a many-to-many relationship between companies and applications.
Having a company (without the apllications relationship loaded from the database) and a collection of application ids, I would like to clear the applications from the company and add the applications with ids specified in the collection.
I can attach applications using their ids, without loading them from the database, like this:
foreach (int id in selectedApplications)
{
Application application = new Application() { Id = id };
_context.Applications.Attach(application);
company.Applications.Add(application);
}
_context.SaveChanges();
But I need to clear the applications relationship first. Is there any way to clear a many-to-many relationship without loading it from the database first?
This is only way. company.Applications must be loaded when you add or remove items from it, otherwise the change tracker will never be aware of any changes.
Also, the junction table is not an entity in the conceptual model, so there is no way to set primitive foreign key properties as is possible in foreign key associations. You have to access the associations by the object collections.

Entity framework Association in conceptual model for one to many relationship

I have two entity CUSTOMER and ORDER..there is one to many relation from CUSTOMER to ORDER where CustomerID is primary key for customer and foreign key in ORDER..now I want to add customer name property from CUSTOMER entity in ORDER entity...I have copied this property and paste it in ORDER table and have added CUSTOMER table and map this property to the CUSTOMER table's same property..but when i trying to validate it vs giving me a Error that is
3024: Problem in mapping fragments starting at line 239:Must specify
mapping for all key properties (ORDER.OrderID) of the EntitySet ORDER
That is not possible in mapping. You cannot add property from Customer table into Order entity this way. Mapping properties from multiple tables to the same entity has very strict rules and it is not possible for this case.
You can expose customer's name in your Order class without defining it in the mapping. Create partial part of Order class and add custom computed property (non mapped):
public partial class Order
{
public string CustomerName
{
get
{
// Customer is navigation property to Customer entity
return Customer.Name;
}
}
}
This will require loading Customer with your Order (eager loading) or using lazy loading. Also this property cannot be used in Linq-to-entities queries.

Entity Framework v1 Modelling Many-to-Many Lookup Table Relationship

I have the following database tables:
Table1: UserUserIdUsername
Table2: RoleRoleIdRolename
Table3: UserRoleUserIdRoleId
A User can have many Roles and a Role can have many Users.
When I model this with EF, I get a User entity with a list of UserRole entities. What I want is a User with a list of Role entities.
Is there a way to model this or query via LINQ to return a User entity and the Role entities they belong to?
Thanks
Dirk
If you model a many-to-many relation, the table in the middle will not appear in your conceptual model. (i.e. you will not have a class "UserRole" derived from "EntityObject")
If you use the EF wizard, ensure that your table "UserRole" only have these two Fields and no others. Also ensure, that you have created the foreign key constraints on both of the fields. if you have, then the wizard will create a proper many-to-many relation.
The query then probably looks something like
using(MyObjectContext context = new MyObjectContext(someParameters)){
var theUser = (from user in context.UserSet
where user.UserId = XY
select user).First();
theUser.Roles.Load();
}

problem with a Many to many relations in Entity framework

I have 3 entities
-Direction
-City
-GeoPosition
each Direction have a Geoposition, and each City have a collection of Geopositions (this represent a polygon)
I have 5 tables
-directions
-cities
-geopositions
-directionsgeopositions
-citiesgeopositions
and EF entities is this
alt text http://img192.imageshack.us/img192/5863/entitydesignerdiagram.png
each entity have function imports for insert, update, and delete
i have this error
Error 2027: If an EntitySet or AssociationSet includes a function mapping,
all related entity and AssociationSets in the EntityContainer must also define
function mappings. The following sets require function mappings: CitiesGeopositions, DepartmentsGeopositions.
I need function imports for the relation tables??
what is the problem?
The answer to your questions are, respectively:
Yes.
See (1).
The Entity Framework allows you to insert/update/delete via DML or stored procs, but it does not allow you to choose "both." If you are going to go to the stored proc route, you must supply procs for every sort of data modification the framework might need to do on an entity, including relation tables.
For a couple of days now, I have been wracking my brains and scouring the Interwebz for information about how to insert data into database intersection tables using the Entity Framework (EF). I’ve hit all the major players’ web sites and blogs and NO ONE has provided straightforward syntax on how to perform this. Out of the blue, the answer occurred to me and I was bound and determined to share this with as many people as I could to lessen the pain I went through.
Let’s set the stage. Assume we have a database relationship as such:
Students (StudentID(PK), StudentName, Gender)
Courses (CourseID(PK), CourseName, CourseDescription)
StudentsCourses (StudentID(PK, FK), CourseID(PK, FK))
For those of you familiar enough with EF, you know that when the relationships above are translated into an entity data model, the Students and Courses tables are created as entities, but the StudentsCourses table is not. This is because the StudentsCourses table does not contain any attributes other than the keys from the other two tables, so EF directly maps the many-to-many relationship between Students and Courses (EF is not limited in the way relational databases are in this respect.) and instead of an entity, translates the intersection table into an AssociationSet. If you weren’t aware of this behavior, check out these links for examples:
http://thedatafarm.com/blog/data-access/inserting-many-to-many-relationships-in-ef-with-or-without-a-join-entity/
http://weblogs.asp.net/zeeshanhirani/archive/2008/08/21/many-to-many-mappings-in-entity-framework.aspx
Now let’s assume that you want to register a current student (ID:123456) for new courses this semester (ENGL101, SOC102, and PHY100). In this case, we want to insert new records into the StudentsCourses table using existing information in the Students table and Courses table. Working with data from either of those tables is easy as they are both an entity in the model, however you can’t directly access the StudentsCourses table because it’s not an entity. The key to this dilemma lies with the navigation properties of each entity. The Student entity has a navigation property to the Course entity and vice versa. We’ll use these to create “records of association” as I like to call them.
Here’s the code sample for associating an existing student with existing courses:
using (var context = TheContext())
{
Student st = context.Students.Where(s => s.StudentID == “123456”).First();
st.Courses.Add(context.Courses.Where(c => c.CourseID == “ENGL101”).First());
st.Courses.Add(context.Courses.Where(c => c.CourseID == “SOC102”).First());
st.Courses.Add(context.Courses.Where(c => c.CourseID == “PHY100”).First());
context.Students.AddObject(st);
context.SaveChanges();
}
Because the associations go both ways, it stands to reason that one could retrieve three Course objects (by CourseID) and associate the same Student object to each, but I haven’t tested that myself. I think it would result in more code than is necessary and might be semantically confusing.
Here’s a code sample that associates a new student with the same existing courses:
using (var context = TheContext())
{
Student st = new Student({ StudentID = “654321”, StudentName = “Rudolph Reindeer”,
Gender = “Male” });
st.Courses.Add(context.Courses.Where(c => c.CourseID == “ENGL101”).First());
st.Courses.Add(context.Courses.Where(c => c.CourseID == “SOC102”).First());
st.Courses.Add(context.Courses.Where(c => c.CourseID == “PHY100”).First());
context.Students.AddObject(st);
context.SaveChanges();
}
And finally, here’s the code to associate a new student with new courses (‘...’ used for brevity):
using (var context = TheContext())
{
Student st = new Student({ ... });
st.Courses.Add(new Course({ ... }));
st.Courses.Add(new Course({ ... }));
st.Courses.Add(new Course({ ... }));
context.Students.AddObject(st);
context.SaveChanges();
}