After adding table Person to database and updating the model from database table, entity Person exists, but is not present in
Entity ctx = new Entity();
ctx.Persons // doesn't exists
How can I fix that? Thanks
Update: table had 2 foreign keys, after I delete one of them - Persons appeared in ctx. Is there any constraint to have 2 foreign keys?
Update №2: EF named table Person as People. WTF???
Ef pluralization of tables for table names is performed unless you specify a table name via annotation or using fluent API modelBuilder.Entity<TPoco>().ToTable("TName", "schema");
Would need to see exception and Custom DBContext class to comment further.
sorry, but you don't provide a lot of context for your question, check some online tutorial like http://blogs.msdn.com/b/webdev/archive/2013/11/01/tutorial-series-updated-for-entity-framework-6-code-first-with-mvc-5.aspx
Related
We have some tables in our database-design which include a column named "PK_ID". This columns are from type "uniqueidentifier" (Guid). The uniqueidentifier points to an entity in another table. So it is basically a Foreign Key column.
The special thing is that there is no constraint on this column. So you can put any uniqueidentifier - value in this column. We have an additional "Type"-column to determine to which table the uniqueidentifier is pointing to.
This certainly does not correspond to the good rules of database design, but it is necessary in our application context and that is not the point.
Our poblem:
When we scaffold our DbContext with dotnet ef dbcontext scaffold EF Core does not recognize the relationships to other tables via the "PK_ID" column. That is not surprising either.
But because this, we cannot use the "Include" and "IncludeThen" methods to build SQL-Join queries.
I hope that was somewhat understandable. How best to deal with this within EntityFramework Core? Is there a way to use methods like "Include" anyway?
You can use fluent syntax when querying for this so you can specify how to join
Syntax looks like this: Taken from here: https://entityframework.net/joining)
var data = context.Authors
.Join(
context.Books,
author => author.AuthorId,
book => book.Author.AuthorId,
(author, book) => new
{
BookId = book.BookId,
AuthorName = author.Name,
BookTitle = book.Title
}
).ToList();
We have a synchronization framework that uses a global SyncEntity table to keep track of which entities have been updated at what time, meaning we have a global table with a structure something like this:
<dbo.SyncEntity>
ID int
EntityType int
EntityGuid uniqueidentifier
The EntityType is an enum that corresponds to the specific entity so that we know in which table to look for this entity.
All our tables have an ID (PK) and a GUID.
I have created a Foreign Key constraint from the different Entity tables and to the EntityGuid in the SyncEntity table.
This works perfect for existing data however when we use EntityFramework to insert new data it doesnt insert the data in the "correct" order resulting in an error because the SyncEntity with the required EntityGuid is not yet inserted.
I guess we could add a property SyncEntity on all of our entities however i really dont want to pollute our domain model with that property.
So my question, is there anyway to ensure that specific Entity types are inserted as the first entities?
Or is there anyway to map the relation from Guid (on the specific Entity) to EntityGuid (on SyncEntity) without a navigation property.
I see two ways you could potentially alleviate this issue.
First, you could use domain events to recognize that a new entity has been created and raise an event, passing in the entity itself as a parameter and then allow that event to create a new SyncEntity insert it and then save it. This will populate your ID and then you can assign it to the new entity creating the relationship.
Second, you could override the SaveChanges method of the DbContext to look at added entities and then create a new record for each of them, then assign your new SyncEntity Ids to the entity.
WHy would you bother EF with something like that?
Have the SyncEntity entry created by a trigger on the tables. Finished. EF does not have to bother with it.
And it is save for direct SQL usage, too.
EF is a good tool - though only a very very mediocre ORM. But it is not a solution for everything. DB internal logic, like a logging table, should be handled in the database.
I am new to Entity Framework so I need help with deleting an object from an entity.
I have 2 tables which are in many to many relationship and an association table connecting them in the database. In the model there are only two tables and the association one is presented by navigation properties as this is how the EF works. Now I need to delete an object from the first table by context.EntityName.DeleteObject(object) but when I try to do it the code fails with error "The DELETE statement conflicted with the REFERENCE constraint FK..", which is a foreign key from the association table to the entity, which object I try to delete. I wonder how to fix this. Could you please help me?
Here is how the tables look like:
Teachers
Teacher_ID
FirstName
LastName
TimetableDetail
TimetableDetail_ID
EducationalDiscipline_ID
Weekday
StartTime
Duration
and the associaion table:
TimetableDetailTeachers
Teacher_ID
TimetableDetail_ID
And here is how I try to delete it:
TimetablesEntities context = new TimetablesEntities();
TimetableDetail detail = context.TimetableDetails.SingleOrDefault(td => td.TimetableDetail_ID == timetableDetailId);
context.TimetableDetails.DeleteObject(detail);
context.SaveChanges();
Thanks in advance!
You just need to clear the association table by clearing the Teachers list for a particular TimetableDetail. Using your code...
TimetablesEntities context = new TimetablesEntities();
TimetableDetail detail = context.TimetableDetails.SingleOrDefault(td => td.TimetableDetail_ID == timetableDetailId);
detail.Teachers.Clear();
context.TimetableDetails.DeleteObject(detail);
context.SaveChanges();
The key line being detail.Teachers.Clear()
Yeah, this is a tricky one.
What you need to do is clear the entities out of the EF's underlying local storage. The example shows what to do when you clear all details for a specific teacher (or even only some details) and then save that teacher's entity. With that in mind, here is some example repository code:
public void EditTeacher(Teacher teacher)
{
if (teacher == null)
{
throw new ArgumentNullException("teacher");
}
YourDbContext.Entry(teacher).State = EntityState.Modified;
// Remove all timetable details that have an orphaned relationship.
// (E.g., orphaning occurs when 'teacher.TimetableDetails.Clear()'
// is called or when you delete one particular TimetableDetail
// entity for a teacher)
YourDbContext.TimetableDetails
.Local
.Where(td => td.Teacher == null)
.ToList()
.ForEach(td => YourDbContext.TimetableDetails.Remove(td));
YourDbContext.SaveChanges();
}
I hope this helps.
For further reading, take a look at: Deleting orphans with Entity Framework.
Edit:
The example code above assumes that elsewhere in your code you have defined and created YourDbContext as a member variable within your repository class. I just wanted to point that out in case it wasn't clear.
You could do:
add row before remove detail:
context.Teachers.RemoveRange(detail.Teachers);
The key line being that...
Say I have the following tables:
Essence, EssenceSet, and Essence2EssenceSet where Essence2EssenceSet holds just the IDs of the 1st 2 tables to form the M:M relationship.
In EF since Essence2EssenceSet has no other fields it is not exposed in the model. I find this makes it difficult to insert records into this table when I already have the 2 IDs needed to create the record but don't necessarily have the Essence and EssenceSet records loaded (Just their IDs)
Is there a way to tell EF to not model this way and always include the join table? Or am I missing an easier way to create these join table records?
You can create M:N relation in EF without retrieving objects as well:
using (var context = new MyContext())
{
var firstEntity = new FirstEntity { Id = firstId };
var secondEntity = new SecondEntity { Id = secondId; }
context.FirstEntities.Attach(firstEntity);
context.SecondEntities.Attach(secondEntity);
firstEntity.SecondEntities = new HashSet<SecondEntity>();
firstEntity.SecondEntities.Add(secondEntity);
context.SaveChanges();
}
Anyway exposing junction table as entity is possible but you will lose comfort of EF and fallback to SQL like approach:
Delete M:N relation created by designer
Add new entity
Add two columns to the new entity representing foreign keys
Map the new entity to junction table
Add associations to related entities
Set referential constraints for added relations
Entity Framework is an ORM, and as such, when you work with it you aren't suppose to think of the database in terms of tables but instead in terms of objects. You shouldn't be inserting the identity into a table that holds the M2M relationship, but you should be loading one side of the relationship, which should expose a collection of the other side and add it to that collection. For a M2M, you may need to load the other side and do the same.
Also, I believe EF prefers all tables to have a single column PK (I could be wrong on this), but you may need to add a column to the M2M and designate it as a PK.
Is it possible to have an association mapping a table to itself?
e.g.
Table:
ConditionId
ConditionName
...
...
ParentConditionId
where we can have many ParentConditionIds each mapping to the same ConditionId.
I've tried a one to many mapping but I'm getting an error when there is no children.
Yes it is possible. Put the FK in your database and the wizard will map it correctly. Make sure ParentConditionId is nullable.
Take a look tutorial which can be download here . It explains in detail how to model self-reference table.