I have two tables like this:
And between these tables there is a Junction table like this:
*appartiene_squadra*
field name (**primary key**)(*foreign key to first table*)
field name (**primary key**)(*foreign key to second table*)
Now, the problem is that the model recognize only the first two tables and I can't write data in appartiene_squadra. How I can write data here?
You're right in identifying that Entity Framework creates the junction table for you.
To enter data, you do not "add data to the junction table". What you do is add data to the navigational property, which will automatically be stored in the junction table by Entity Framework.
using(var db = new MyDataContext())
{
Installatori myInstallatori = db.GetExistingInstallatori(); //Assume this gives you an existing entity
Squadra mySquadra = db.GetExistingSquadra(); //Assume this gives you an existing entity
//You can do it this way
myInstallatori.squadra.Add(mySquadra);
//or this way
mySquadra.installatori.Add(myInstallatori);
//And then you save it to the database
db.SaveChanges();
}
I've shown an example of adding A to B, and B to A. Please note that you should only do one of these at the same time (at least when it is your intention to save to the database, rather than simply populating the entity in memory).
Also, to remove a row from the database:
mySquadra.installatori.Remove(myInstallatori);
db.SaveChanges();
Related
I am using C# to select data from my database. Now i have two table, the first one is aspnetuser, the second one is aspnetuserroles, the aspnetuserroles have the foreign key linkage with aspnetuser table, when i perform the following query
db.AspNetUsers.ToList()
the aspnetroles data will appeared in the aspnetusers data. This will cause my datatable unable to display its data because datatable expect one value in one column parameter. If the aspnet roles data inside that json, it will appear as multiple row and datatable dont accept it.. If i remove that foreign key linkage, my datatable will display without any error.
In this case, what i want is, how to select aspnetusers table without pulling out its foreign table. For eg
db.AspNetUsers.Select(x=>x.AspNetUsers).ToList();
Turn off the LazyLoading. So that the children will not be fetched automatically.
try doing something like this (good for keeping the return object light and leave behind any unwanted columns):
(I have just made up some col name, but you get the idea.)
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
othercol1 = a.othercol1,
othercol2 = a.othercol2,
}).ToList();
Footnote: In reality it is generally not good practice to return the actual db Entity to the front end so you might want to have your own Data Transfer Objects (DTO).
You configured that in the mappings using the Fluent API's methods
HasOptional
HasMany
Ignore
etc. But normally, I create schema-bound views in database and then map that in EF. It works really well in cases when we're only interested in a flattened query without all the joints.
Or use Linq to EF projections as JonhB's answer...
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
...
}).ToList();
Just make sure you don't call ToList on db.AspNetUsers because that would materialize the query on AspNetUsers and all it's foreign key references and as result the projection is done in-memory after the query returns
I have one table that has many fields like ID,Username,Password,Lang,Date,..
When I create Entity Data modeling so all the table field is generated.
I want to generate only specific column like username and password only.
When you generate from database it will generate model for all the columns initially, but you have the freedom to delete the columns that you don't want manually from the generated database EDMX diagram.
Just select the field you don't want and hit 'DEL' key.
Make sure that the fields you delete are nullable ones and also not primary key for that table.
I use Entity Framework 4 on C# Winforms.
I have a SQL Server database with 2 tables like this:
Users table:
UserId (int) (PK)
UserName
Products table:
ProductId (int)(PK)
ProductTitle
UserId1 (int) (foreign key referencing `UserId` in `Users` table)
UserId2 (int) (foreign key referencing `UserId` in `Users` table)
I am modeling SQL Server database in my C# project with Entity Framework (including foreign key columns in model).
Then I get records with this code:
Entities dbEnteties = new Entities();
dbEnteties.ContextOptions.LazyLoadingEnabled = false;
var dbe = dbEnteties.Products.Include("Users");
var result = dbe.ToList();
When I get records from database I see that the UserId1 field has data but UserId2 field is Null.
What's wrong with my C# code? And how can I solve this problem?!
It's perfectly okay for you to have two foreign keys in the Products table pointing to the Users table. I do this all the time, and your reason for doing it is fine.
Since you have turned Lazy Loading off, you need to explicitly ".Include" the navigation properties if you want the query to automatically load them. You're going to have to figure out what the names are for the navigation properties that Entity Framework created automatically for you. I'm assuming you are using the "Database First" model. If that's the case, then double click on your .EDMX file and look at the Products table. You should see a section there called "Navigation Properties". They might be called "User" and "User1". If this is the case, then you need to do the following. Since you have two separate relationships between the tables, you will need two separate ".Include" statements:
dbEnteties.Products.Include(product => product.User);
dbEnteties.Products.Include(product => product.User1);
(Make sure to include using System.Data.Entity; at the very top of your file, otherwise the lambda syntax will not work.)
I have an audit trailing system in my project from http://doddleaudit.codeplex.com/.
As you can see on this image it records the EntityTable - which is the table name, and the EntityTableKey - which is the primary key
I would like to associate the audit records with the tables it had recorder, then query the result in linq to sql. But the problem is if the audit table has record for orders and record for products it will never know just by the primary key, where does the record belong, thus i need to use the table name as part of the key.
So the question is: Is it possible to create a relation that will have a composite primary key that contains the table name in it?
AuditRecord to Orders
AuditRecord to Products
You could do it, but I would recommend a bit different approach.
Don't use char/varchars/nvarchar in your PK/FK, it bloats the index. I would rather create another table that will hold TableId/TableName pairs of all your tables (you can use sys.tables.object_id for your id if you wish) and have a FK in AuditRecords to it. Then establish composite key between AuditRecords and AuditRecordFields (Id, TableId).
Another thing:
EntityTable and AssociationTable should be of sysname type
AuditDate can be of type Date (available from SQL Server 2008)
EDIT:
If you like to access audit records from each object, you can create a base class for your audited objects and implement following method (beware, it's untested):
public IQueryable<AuditRecord> AuditRecords
{
get
{
MyContext ctx = new MyContext();
var ars = from ar in ctx.AuditRecords
where ar.EntityTable.Equals(this.GetType().Name)
select ar;
return ars;
}
}
I have 2 tables; PriceList and PriceListDetail with one to many realitonship. After inserting a new PriceList and I need to copy PriceListDetail's of an existing PriceList.
var pricedetails= db.PriceListDetails.Where(p => p.PriceList Id == SomeExistingPriceListID);
All I need is to change priceListID of pricedetails above and Insert them to PriceListDetail table. When I modify priceListId of pricedetails and try to insert them I get 'cannot insert entities that already exists'.
Obvious solution is to create new entities and copy values one by one from pricedetails then insert.
Is there a way to avoid one by one copying? Maybe create duplicate rows then modify duplicated ones?
Entity frameworks uses another key than your primary key, and it is called an entity key.
So having your PriceListDetails, all you have to do is to change the primary key ID and set the entity key to NULL (NULL means a new row).