I am using Entity Framework Reverse POCO generator v2.37.5.
I need to map an external database. It is not possible for me modify the schema. But the tables don't have primary key and all columns are set to null.
However, the combination of certain columns will always be unique. For example, the following 3 columns can be combine to form the primary key:
Is there any setting in the template that helps me to set combination of columns as primary key?
Any suggestion / direction will be greatly appreciated.
First, find your Entities.ttinclude
file.
<#+ #>
blocks) and move it to a new file named Entities.ttinclude.cs
<#@ Include File = "Entities.ttinclude.cs" #>
to the Entities.ttinclude
file.Entities.ttinclude.cs
to None
.Look for this somewhere around lines 250-320:
Settings.UpdateColumn = (Column column, Table table) =>
Inside the function you can tell EF that there totally is a PK defined on this table, I pinky-swear! like so:
Settings.UpdateColumn = (Column column, Table table) =>
{
// ...
if( column.ParentTable.Name == "Memb" )
{
switch( column.Name )
{
case "EnrollNumb":
case "CubNumb":
case "SeqVal":
column.IsNullable = false; // PK columns cannot be NULLable.
column.IsPrimaryKey = true;
column.PrimaryKeyOrdinal = column.Ordinal;
column.ParentTable.HasPrimaryKey = true
break;
}
}
// ...
}
Run Model.tt
Assuming no errors happened, take a look at the folder with the generated .cs
files, look for Memb.Configuration.cs
. It should look something like this:
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.37.1.0")]
internal class MembConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Memb>
{
public MembConfiguration( String schema )
{
ToTable( "Memb", schema );
HasKey( x => new { x.EnrollNumb, x.CubNumb, x.SeqVal } );
Property( x => x.EnrollNumb ).HasColumnName( "EnrollNumb" ).HasColumnType( "nvarchar" ).IsRequired().MaxLength(10);
Property( x => x.CubNumb ).HasColumnName( "CubNumb" ).HasColumnType( "nvarchar" ).IsRequired().MaxLength(50);
Property( x => x.SeqVal ).HasColumnName( "SeqVal" ).HasColumnType( "nvarchar" ).IsRequired().MaxLength(5);
// other columns here
}
}
And you should be able to build your project, then run it, and it should just work.
You can also define fake Foreign Key constraints and set-up other kinds of relationships and EF will believe you, which is handy for when you want EF to handle a VIEW
as though it were a TABLE
, especially as a VIEW
in SQL Server cannot be imbued with PK and FK constraints (you can also get DML working provided your VIEW
is updatable).