I got a question about foreign key when "importing" the db into visual studio.
my development environment:
SQL 2005/2008/2008R2
Visual Studio 2008 ASP.NET MVC 2 with .Net framework 3.5 SP1
was following the MVC music store V1.0
in the tutorial pdf, page 50, it says when we creating the "Entity Data Model" at the last stage, we should select "Include foreign key columns in the model.
however, i am using VS2008 and when at this stage there is no such foreign key option to choose.
plz notice that inside the red circle, it should contain (AlbumId, GenreId, ArtistId, Title, Price, AlbumArtURL) as shown in tutotial
but my model is missing GenreId and ArtistId.
how to deal with it?
I encountered a problem later when the i creating edit form and need to use something like [[[[<%= Html.LabelFor(model => model.GenreId) %>]]]]] it is not working.
so i need the GenreId and ArtistId to appear in the Album. i guess it is about the foreign key problem...
do you know how to solve it?
Thanks a lot!!!
It is not possible. Importing foreign key columns is feature of EFv4 so you need .NET 4.0 and Visual Studio 2010 to use it.
In your case you must access FK value through EntityObject based API. Your entity should have property like GenreReference so you can use something like:
int genreId = (int)entity.GenreReference.EntityKey.EntityKeyValues[0];
Related
I was wondering how to add a unique constraint while in the Entity Designer in Visual Studio 2015. All the answers that I've found only talk about adding a unique constraint in the generated C# code or in the generated sql.
Is there a way to do this in the designer itself?
I had to import data from firebird database to Entity Framework, in order to do so I'v installed .net provider and DDEX Provider for visual studio.
My problem occurs when I was adding any table to model the erros says
"Key Part: 'SomeColumn' for type MyTable is not valid. All parts of the key must be non nullable.**"
It does't matter if I'am trying to import one table or many tables, I always had the same error.
What I have to do ?
Any Ideas ? I will appreciate any help.
I solved the problem.
All I need to do is right click on model.edmx ->Open with ->XML Text Editor and remove all but one which is appropiate ID of table.
I am fairly new to ADO.NET. I am ok with all the basic INSERT, etc. But now, I have a problem inserting a record into a table that contains a foreign key. I have done some research but am still stuck ... so here goes:
I want to INSERT a new record into a table called Professionals. It has a foreign key mapped to a different table. The FK is WAPublicUserID.
See Image:
When I create a data model, the WAPublicUserID isn't listed in the Properties of the Professional data model.
See Image:
Therefore, when I try to create an INSERT in my code, the WAPublicUserID field can't be found and I can't insert the record. The WAPublicUserID that I wish to use already exists in the WAPublicUser table that the FK is mapped to.
See Image:
How do I go about Inserting a new record in the Professionals table that contains a foreign key to an existing record in the WAPublicUser table? Thanks!
Someone has set "Include Foreign Key Properties in Model" to false.
Hence you have the navigation property of WAPublicUser but not the ForeignKey property.
This means you will have to Attach the relevant WAPublicUser object to the WAPublicUser property on the object you are trying to save.
I'd need a lot more code to know exactly what you are doing, but the basics of it are as follows:
If the WAPublicUser already exists:
Grab the existing entity from the database - OldEntity.
Update the OldEntity with the properties of the new one you are currently trying to save.
Save the (now updated) Old entity back to the database - because you have just read it, it should have the WAPublicUser reference already set.
If it doesn't:
Create a new WAPublicUser
Set the WAPublicuser property of the Professional object to the newly created WAPublicUser - that line goes where your code stops above.
myEnt.AddToProfessionals(pro);
myEnt.SaveChanges();
Got it. Here's how it works, in case anyone else reads this. #1 and #2 are focal points.
Mucho thanks to #BonyT for getting me on the right path ...
using (JONDOEntities myEnt = new JONDOEntities())
{
// #1) Need to create WAPublicUser object first
var wap = (from w in myEnt.WAPublicUsers
where w.WAPublicUserID == 981
select w).FirstOrDefault();
var proUser = (from p in myEnt.Professionals
where p.WAPublicUser.WAPublicUserID == wap.WAPublicUserID
select p).FirstOrDefault();
// If the record does not exist in the Professional table, insert new record.
if (proUser == null)
{
JONDOModel.Professional pro = new JONDOModel.Professional()
{
ProfessionalType = "unknown",
FirstName = "unknown",
LastName = "unknown",
PhoneNumber = "unknown",
WebsiteUrl = "unknown",
TaxID = "unknown",
BusinessInfo = "unknown",
ProfessionalLogo = "unknown",
IsApproved = true,
CATaxExempt = false,
WAPublicUser = wap // #2) Plug in the WAPublicUser object here
};
myEnt.AddToProfessionals(pro);
myEnt.SaveChanges();
}
OK, here's the real answer to my OP:
The asp.net website that I took over to manage was targeting .NET 3.5. Apparently, there are some issues with 3.5 and Entity Framework.
I converted the website to target .NET 4.0(*see below to see how). When I went to create the entity data model, voila , by default, it now included the Foreign Keys and therefore, I did not have any issues as described in OP.
If you run into this situation, you have to make sure that the web server is also upgraded to .NET 4.0. Because if you upgrade/convert the website files to target .NET 4.0, but your web server hasn't been upgraded, then although the website runs smooth on your dev machine (assuming that it has .NET 4.0 framework), it will crash on the live web server.
As an aside, .NET 4.0 framework will run apps that were built using previous versions of .NET (backward compatibility) ... however, an app that targets .NET 4.0 will not run in an environment with .NET 3.5 framework or prior.
CONVERT WEBSITE TO .NET 4.0:
Two ways to convert/upgrade website to .NET 4.0. 1) Usually, when you open a fresh copy and it's targeting 4.0, visual studio will ask if you want to convert/upgrade (Choose YES). 2) Within visual studio (commercial version), click WEBSITE tab, START OPTIONS, BUILD ... then you should see the options to change the "Target Framework" ...
I have database tables that look like this:
A Task can be mapped to a Module, or not mapped at all (0...1). I'm using Entity Framework database-first, and when I generated the model from the database, the Task entity came through with Modules as a collection (0 or more). So I opened up my EDMX and changed the "Modules" navigation property on Task to 0...1.
Now, when I attempt to compile, I get this error:
Error 3003: Problem in mapping fragments starting at line 1241:Given the cardinality of Association End Member Task, it should be mapped to key columns of the table TaskModule. Either fix the mapping or change the multiplicity of this end.
I don't understand what I need to do to fix this. I've looked at the association details and can't see the issue. I know I'm probably missing something stupid, but am totally stuck. Association properties:
Visual Studio 2010 SP1, Entity Framework 4.3.1.0, SQL Server 2008 R2.
One way to do this is to redefine the primary key for the TaskModule table. Instead of the primary key being (TaskId, ModuleName) it needs to be just (TaskId). Then do an update model from database and change any of the associations manually that didn't get picked up from that update.
Well your database schema is not correct with the description you give :
the TaskModule table implicates a many-to-many relationship, not a many-to-oneOrZero.
In edmx, many-to-many relation tables are not displayed, but they still exist in database.
So you should fix your database, or be happy with the relation proposed by EF !
The answer to my question should be quite obvious, but I cannot find it. I have a edmx file that has one table. There is a field of type string. EF always generates nvarchar for that (which is kind of expected), but I need an ntext instead of nvarchar for that field as 4000 is too small for me.
So tell me - what is the proper way to tell EF to generate ntext fields?
PS Using Entity Framework 4, SQL CE 3.5
I guess you are using model first, don't you? You can simply create custom T4 template for SQL DDL generation and include logic which will use NTEXT when field is defined with max size.
Default template is on:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\SSDLToSQL10.tt
Just copy this template and find the logic where data type is created. Once you have your template change DDL Generation Template in model properties (in the designer) to your modified version.
There is much more you can do with generation template because you can add some annotations to your model (XML) and use them for custom logic in the SQL generation process.
Just set the property "MaxLength" in the Designer to "Max". This will generate a ntext field in the SQL CE DB.
If your project contains an ADO.Net Entity Data Model (.edmx) then see Ladislav's excellent answer.
But if you're using the Code First libraries and your project doesn't contain a .edmx then you can use the System.ComponentModel.DataAnnotations.ColumnAttribute to specify the column type:
using System.ComponentModel.DataAnnotations;
public class Note {
[Column("Note", TypeName="ntext")]
public string Note { get; set; }
}