Entity Framework ConnectionString in App Config with duplicated table - sql-server

For some reason I have a database with three types of tables with the same name but the prefix is different. The schema of database is this:
I must implement only the dbo.SpRicezioneSpedizioniLight tables manually and I have realized there are these two classes:
public class SpRicezioneSpedizioniLight
{
public string AudOperation { get; set; }
public Nullable<System.DateTime> AudDateLog { get; set; }
public int PROGRESSIVO { get; set; }
}
public class GemapDbContext : DbContext
{
public DbSet<SpRicezioneSpedizioniLight> SpRicezioneSpedizioniLights { get; set; }
}
How can I identify the specific table dbo.SpRicezioneSpedizioniLight? For now my connection string is:
<add name="SABIntegrationEntities" connectionString="metadata=res://*/Models.ModelTest.csdl|res://*/Models.ModelTest.ssdl|res://*/Models.ModelTest.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=SABIntegration;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
All of this works fine in a local database with a single table.
Thank you

The "prefix" of your tablename is the name of the schema this table is associated with. "dbo" is the default schema name used by EF.
You can change the default schema by using
modelBuilder.HasDefaultSchema(SchemaName);
in your OnModelCreating-Method or map your other type to the type explicitly using
modelBuilder.Entity().ToTable("SpRicezioneSpedizioniLight", "bak");

Related

Entity Framework Core Migration fails in Case of Change to ValueGenerationStrategy

I have annotated some of my model classes' keys with [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
and added a migration.
When running Update-Database I keep getting following error message:
To change the IDENTITY property of a column, the column needs to be dropped and recreated.
I also tried to Update-Database with a complete new database, to no avail as the error is the same.
When changing the identity property in SQL Server Management Studio, I do not get such error but I would like to avoid a mix of code and DB first approach.
Is there a way to either
force the update to drop and recreate the column
or drop and recreate the table ?
EDIT1:
To answer a question from the comments. My model class before looked like:
public partial class MyModel
{
[Key]
public int Id { get; set; }
[MaxLength(70)]
public string Name { get; set; }
public string Description { get; set; }
...
}
This is my model class after adding the annotation:
public partial class MyModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(70)]
public string Name { get; set; }
public string Description { get; set; }
...
}

How can Entity Framework connect to a SQL Server view rather than table? [duplicate]

I am developing a contact log in a website using VS 2010, MVC3 and EF 5 - the entities are created using code first. The data is stored in an SQL Server 2008 R2 set of databases. I want to display a summary of the contact log and have created a view.
CREATE VIEW dbo.ContactLogSummaries
AS
SELECT
CLE.ContactLogEntryID,
CLE.CaseID,
'Test' AS ContactName,
EU.UserName As OfficeUser,
CLE.DateAndTimeOfContact,
CLC.Category,
CLE.ContactDetails
FROM
ContactLogEntries AS CLE
JOIN
ContactLogCategories AS CLC
ON CLE.ContactLogCategoryID = CLC.ContactLogCategoryID
JOIN
Control.dbo.EndUsers AS EU
ON CLE.UserID = EU.EnduserID
There are two entities in the Contact Log database (ContactLogEntries and ContactLogCategories) and a database first entity Control.dbo.EndUsers in another database. The contact log could contain a large number of records. I want to be able to display just the records for a specific case.
My question is in two parts:
Can I use the SQL view directly to display a summary on a web page (perhaps by reading it into a class)
Can I create a code first object equivalent to the SQL view.
You can just map the Entity directly to the view using TableAttribute (data annoations), or ToTable in your Fluent Mappings...
For example using data annotions:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public namespace whatever.mynamespace
[Table("dbo.ContactLogSummaries")] //<-- this is your view
public class ContactLogSummary
{
...
}
}
Found a simple solution to question 1:
public class ContactLogSummary
{
public int ContactLogEntryID { get; set; }
public int MaternalCaseID { get; set; }
public String ContactName { get; set; }
public String OfficeUser { get; set; }
public DateTime DateAndTimeOfContact { get; set; }
public String Category { get; set; }
public String ContactDetails { get; set; }
public static List<ContactLogSummary> LoadContactListSummary
(int caseID, String connectionString);
{
MyDataContext dbContext = new MyDataContext(connectionString);
return dbContext.Database.SqlQuery<ContactLogSummary>
("SELECT * FROM dbo.ContactLogSummaries WHERE MaternalCaseID = #CaseID ORDER BY ContactLogEntryID DESC",
new SqlParameter("CaseID", caseID)).ToList();
}
It does all that's required so, although I'm interest in an answer to question 2 I have a working solution.

Database Migration doesn't work in sqlserver 2012

Database creation and migration works in sql 2008,but it does not work in sql2012.
Error : "Column 'IpAddress' in table 'ePoll.Answer' is of a type that is invalid
for use as a key column in an index."
propery in model :
[MaxLength(39)]
[Index(IsClustered = false)]
public string IpAddress { get; set; }
Database migration works when i use [Required] attribute.
[Required]
[MaxLength(39)]
[Index(IsClustered = false)]
public string IpAddress { get; set; }

Entity framework, Data annotations [DatabaseGenerated(DatabaseGeneratedOption.Identity)] and sequential GUID

I'm trying to use the entity framework to communicate with my existing DB. This is thus DB first. Using sql server and c#. The problem is that I would like to use a sequential GUID, generated by the database.
Each time I run the code, my controller pastes the GUID assigned to lutRoughagePhysicalSiloId to the DB (most of the time lutRoughagePhysicalSiloId is just an empty GUID (000..) since I don't fill it). As far as I can see, this should not be happening since I use [DatabaseGenerated(DatabaseGeneratedOption.Identity)].
Any Ideas?
SQL code
CREATE TABLE [dbo].[lutRoughagePhysicalSiloType]
(
[RoughagePhysicalSiloTypeId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY UNIQUE DEFAULT NEWSEQUENTIALID(),
[PhysicalSiloTypeName] NVARCHAR(50) NOT NULL UNIQUE
)
(Notice the Default value newsequentialId() that gets generated as default by sql server)
Automatic created modelview (DB first):
namespace guiIlvoDairyCowBarn.Models
{
using System;
using System.Collections.Generic;
public partial class lutConcentratePhysicalSiloType
{
public lutConcentratePhysicalSiloType()
{
this.lutConcentratePhysicalSiloes = new HashSet<lutConcentratePhysicalSilo>();
}
public System.Guid ConcentratePhysicalSiloTypeId { get; set; }
public string PhysicalSiloTypeName { get; set; }
public virtual ICollection<lutConcentratePhysicalSilo> lutConcentratePhysicalSiloes { get; set; }
}
}
Buddy class
namespace guiIlvoDairyCowBarn.Models
{
[MetadataType(typeof(lutRoughagePhysicalSiloMD))]
public partial class lutRoughagePhysicalSiloType
{
public class lutRoughagePhysicalSiloMD
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public System.Guid RoughagePhysicalSiloTypeId { get; set; }
[Required, DisplayName("Physical silo type")]
public string PhysicalSiloTypeName { get; set; }
public virtual ICollection<lutRoughagePhysicalSilo> lutRoughagePhysicalSiloes { get; set; }
}
}
}
what is a Buddy class suppose to mean?
Using both [Key] and the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] should work and ignore any user provided value. After saving to the DB the property should have the DB generated Guid.
Your class lutConcentratePhysicalSiloType has no EF data annotations and if saved would take the values you provided. NewSequentialId() is a default and without any EF data annotations the DB row will get whatever the value you specify in the C# class.

Using schema names with SQL Server & ServiceStack.OrmLite

Anyone know how to apply the correct Alias attribute to query tables with schema names?
I have a table called accounts.register. I've tried using [Alias("accounts.register")] as the class decorator attribute for Register class but this doesn't work.
If I change the schema to dbo then I can remove the alias and everything works. Unfortunately I have a legacy system with many schemas so I need this to work.
OK I figured it out. Along with the Alias attribute is the Schema attribute. The former is in the ServiceStack.DataAnnotations namespace but the latter is in the ServiceStack.OrmLite namespace. Here's an example to map fields field1 & field2 to/from myschema.mytable:
using System;
using ServiceStack.OrmLite;
using ServiceStack.DataAnnotations;
[Schema("myschema")]
[Alias("mytable")]
public class MyEntity
{
[PrimaryKey]
[AutoIncrement]
public long Id { get; set; }
[Alias("field1")]
public string SomeField1 { get; set; }
[Alias("field1")]
public string SomeField2 { get; set; }
}

Resources