I am using sql server 2008, to follow the latest convention I used new schema other than [dbo].[tablename] which is now look like this [newdbo].[tablename]. The problem now, SimpleRepository could not locate [newdbo].[tablename], I assumed it is looking for [dbo] rather than [newdbo], since my class is define as:
here's my Table: Schema/owner is "kiss"
CREATE TABLE [kiss].[Users](
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](20) NOT NULL,
[UserPassword] [varbinary](128) NULL,
[UserTypeID] [tinyint] NOT NULL,
[ByPassAccessRestrictionsFlag] [bit] NOT NULL,
[IsEnforcePasswordPolicy] [bit] NOT NULL,
[PasswordExpirationDate] [datetime] NULL,
[IsPwdChangeNextLogin] [bit] NOT NULL,
[ShowLatestNewsFlag] [bit] NOT NULL,
[SortRowNumber] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[CreatedBy] [nvarchar](20) NOT NULL,
[UpdatedDate] [datetime] NOT NULL,
[UpdatedBy] [nvarchar](20) NOT NULL,
[DeletedDate] [int] NULL,
[eCrewID] [varchar](10) NULL,
[EntityTypeID] [int] NOT NULL
)
GO
and here is my class:
public class Users
{
public Int32 ID { get; set; }
public String UserName { get; set; }
public Byte[] UserPassword { get; set; }
public Byte UserTypeID { get; set; }
public Boolean ByPassAccessRestrictionsFlag { get; set; }
public Boolean IsEnforcePasswordPolicy { get; set; }
public DateTime PasswordExpirationDate { get; set; }
public Boolean IsPwdChangeNextLogin { get; set; }
public Boolean ShowLatestNewsFlag { get; set; }
public Int32 SortRowNumber { get; set; }
public DateTime CreatedDate { get; set; }
public String CreatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
public String UpdatedBy { get; set; }
public Int32 DeletedDate { get; set; }
public String eCrewID { get; set; }
public Int32 EntityTypeID { get; set; }
}
running a simple code:
var repo = new SimpleRepository("kiss", SimpleRepositoryOptions.None);
var users = repo.All<Users>();
gvUsers.DataSource = users;
gvUsers.DataBind();
yield an error:
System.Data.SqlClient.SqlException was unhandled by user code
Message="Invalid object name 'Users'."
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=208
Procedure=""
Server="(local)\\SQLEXPRESS"
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at SubSonic.DataProviders.DbDataProvider.ExecuteReader(QueryCommand qry)
at SubSonic.Linq.Structure.DbQueryProvider.Execute[T](QueryCommand`1 query, Object[] paramValues)
at lambda_method(ExecutionScope )
at SubSonic.Linq.Structure.DbQueryProvider.Execute(Expression expression)
at SubSonic.Linq.Structure.QueryProvider.System.Linq.IQueryProvider.Execute(Expression expression)
at SubSonic.Linq.Structure.Query`1.System.Collections.IEnumerable.GetEnumerator()
at System.Web.UI.WebControls.PagedDataSource.GetEnumerator()
at System.Web.UI.WebControls.GridView.CreateAutoGeneratedColumns(PagedDataSource dataSource)
at System.Web.UI.WebControls.GridView.CreateColumns(PagedDataSource dataSource, Boolean useDataSource)
at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data)
at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
at System.Web.UI.WebControls.GridView.DataBind()
at web_subsonic._Default.Page_Load(Object sender, EventArgs e) in C:\scr\wcsf_playground\Modules\web_subsonic\web_subsonic\Default.aspx.cs:line 25
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
What's the default schema for your login? Unfortunately there's no way your object will know what schema you're working with - this is app ---> db remember, so if you have a separate schema you should use a login which uses that schema by default.
There are two options
First, get the latest source code, and modify the souce code
Find the SchemaAttributes.cs, add code:
[AttributeUsage(AttributeTargets.Class)]
public class SubSonicTableSchemaAttribute : Attribute
{
public SubSonicTableSchemaAttribute(string schema)
{
Schema = schema;
}
public string Schema { get; set; }
}
Bind the SubSonicTableSchemaAttribute to User Class
[SubSonic.SqlGeneration.Schema.SubSonicTableSchema("kiss")]
public class User{...}
Find Objects.cs file, Add code to the "public static ITable ToSchemaTable(this Type type, IDataProvider provider)" Method
var typeAttributes = type.GetCustomAttributes();
foreach (var typeAtt in typeAttributes)
{
if(typeAtt.ToString().Equals("SubSonic.SqlGeneration.Schema.SubSonicTableSchemaAttribute"))
{
var schema = (SubSonicTableSchemaAttribute) typeAtt;
result.SchemaName = schema.Schema;
}
}
Second, have a look at my demo:
Use subsonic 3.0 SimpleRepository to a existing database
Related
I'm trying to insert a clan entity to Clan container. My partition key is id and the model is like this:
public class Clan
{
public string Id { get; set; }
public string ClanName { get; set; }
public int MembersCount { get; set; }
public int Capacity { get; set; }
public int WHP { get; set; }
public int LogoId { get; set; }
public AppMarketType AppMarket { get; set; }
}
ClanDbContext:
public class ClanContext : DbContext
{
public ClanContext(DbContextOptions<ClanContext> options)
: base(options) { }
public DbSet<Clan> Clans { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Clan>()
.HasNoDiscriminator()
.ToContainer("Clans")
.HasPartitionKey(p => p.Id)
.Property(x => x.Id).ToJsonProperty("id");
}
}
All I want to do is:
try
{
var clan = new Clan
{
Id = Guid.NewGuid().ToString(),
AppMarket = Core.AppMarketType.GooglePlay,
ClanName = "Blazers",
Capacity = 110,
LogoId = 342,
MembersCount = 34,
WHP = 1280
};
_clanContext.Add(clan);
_clanContext.SaveChanges();
}
catch (Exception)
{
throw;
}
It throws an exception:
StartIndex cannot be less than zero. (Parameter 'startIndex')
Callstack:
at System.Text.StringBuilder.Remove(Int32 startIndex, Int32 length)
at Microsoft.EntityFrameworkCore.Cosmos.ValueGeneration.Internal.IdValueGenerator.NextValue(EntityEntry entry)
at Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator.Next(EntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.ValueGenerationManager.Generate(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
at Dummy.Web.Services.ClanService.<IncreaseWHP>d__6.MoveNext() in C:\Repositories\dummysolution\Domain\dummydomain\Services\ClanService.cs:line 50
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Clans.JoinGroup.<Run>d__2.MoveNext() in C:\Repositories\dummysolution\API\dummyapi\Clans\JoinGroup.cs:line 55
After confirm with contributor, this issue was fixed in Microsoft.EntityFrameworkCore.Cosmos 5.0.0.
If you are using a version before 5.0.0, please try after upgrading.
If you are getting a similar exception in 5.0.0 or later please file a new issue and include a small project that demonstrates it.
Related Issue:
Cannot create new item in collection
We are having to call a stored procedure within a foreach loop of the ARTran records to update a different set of ARTran records based on 2 values from the original recordset of ARTran records. Our code validated and published but we are getting the following error when we click Process.
1/9/2018 10:52:52 AM Error:
Failed to convert parameter value from a PXResultset`1 to a String.
System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType,
IFormatProvider provider)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value,
MetaType destinationType, Boolean& coercedToDataFeed, Boolean&
typeChanged, Boolean allowStreaming)
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value,
MetaType destinationType, Boolean& coercedToDataFeed, Boolean&
typeChanged, Boolean allowStreaming)
at System.Data.SqlClient.SqlParameter.GetCoercedValue()
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean
isCommandProc)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc,
Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema,
SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry,
SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource`1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSou
rce`1 completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at PX.Data.PXSqlDatabaseProvider.Execute(String procedureName,
PXSPParameter[] pars)
at PX.Data.PXDatabase.Execute(String procedureName, PXSPParameter[]
pars)
at DocCenter.UpdateLastNotified.b__0()
at PX.Data.PXLongOperation.<>c__DisplayClass17_0.b__0()
Here is the code that we have for the processing. Can anyone advise me on what the issue is here?
using System;
using System.Collections;
using System.Linq;
using PX.Data;
using PX.SM;
using PX.Objects.AR;
using PX.Objects.CR;
using PX.Objects.IN;
namespace DocCenter
{
public class UpdateLastNotified : PXGraph<UpdateLastNotified>
{
public PXFilter<UpdateLastNotifiedFilter> MasterView;
public PXCancel<UpdateLastNotifiedFilter> Cancel;
[PXFilterable]
public PXSelectJoin<ARTran,
InnerJoin<InventoryItem, On<ARTran.inventoryID, Equal <InventoryItem.inventoryID>>,
InnerJoin<ARInvoice, On<ARTran.refNbr, Equal <ARInvoice.refNbr>>,
InnerJoin<ItemBaseDocument, On<InventoryItemExt.usrDocumentNumber, Equal<ItemBaseDocument.baseDocumentCode>>,
InnerJoin<Contact, On<ARTranExt.usrContactID, Equal<Contact.contactID>>>>>>,
Where<ARTranExt.usrDateNotified, Less<ItemBaseDocument.revisionDateReceived>>> DetailsView;
public UpdateLastNotified()
{
Cancel.SetCaption("Clear Filter");
this.DetailsView.Cache.AllowInsert = false;
this.DetailsView.Cache.AllowDelete = false;
this.DetailsView.Cache.AllowUpdate = true;
}
protected virtual IEnumerable detailsView()
{
UpdateLastNotifiedFilter filter = MasterView.Current as UpdateLastNotifiedFilter;
PXSelectBase<ARTran> cmd = new PXSelectJoin<ARTran,
InnerJoin<InventoryItem, On<ARTran.inventoryID, Equal <InventoryItem.inventoryID>>,
InnerJoin<ARInvoice, On<ARTran.refNbr, Equal <ARInvoice.refNbr>>,
InnerJoin<ItemBaseDocument, On<InventoryItemExt.usrDocumentNumber, Equal<ItemBaseDocument.baseDocumentCode>>,
InnerJoin<Contact, On<ARTranExt.usrContactID, Equal<Contact.contactID>>>>>>,
Where<ARTranExt.usrDateNotified, Less<ItemBaseDocument.revisionDateReceived>>>(this);
return cmd.Select();
}
public PXAction<UpdateLastNotifiedFilter> Process;
[PXProcessButton]
[PXButton(CommitChanges=true)]
[PXUIField(DisplayName = "Process")]
protected virtual IEnumerable process(PXAdapter adapter)
{
PXLongOperation.StartOperation(this, delegate()
{
foreach(ARTran tran in DetailsView.Select())
{
if (tran.Selected==true)
{
ARTranExt tranExt = tran.GetExtension<ARTranExt>();
ARInvoiceEntry tranEntry = new ARInvoiceEntry();
tranExt.UsrDateNotified = MasterView.Current.DateNotified;
tranEntry.Transactions.Update(tran);
tranEntry.Save.PressButton();
int? companyid = PX.Common.PXContext.GetSlot<Int32?>("singleCompanyID");
var sp_MySP_Parms = new PXSPParameter[4];
PXSPParameter p1 = new PXSPInParameter("#I_vBaseDocumentCode", PXDbType.NChar, DetailsView.Select("BaseDocumentCode"));
PXSPParameter p2 = new PXSPInParameter("#I_vEmail", PXDbType.NChar, DetailsView.Select("EMail"));
PXSPParameter p3 = new PXSPInParameter("#I_vCompanyID", PXDbType.Int, companyid);
PXSPParameter p4 = new PXSPInParameter("#I_vDateNotified", PXDbType.DateTime, MasterView.Current.DateNotified);
sp_MySP_Parms[0] = p1;
sp_MySP_Parms[1] = p2;
sp_MySP_Parms[2] = p3;
sp_MySP_Parms[3] = p4;
object[] ret = PXDatabase.Execute("icanUpdateDateLastNotifiedForBaseDocumentAndEmail", sp_MySP_Parms);
}
}
}
);
return adapter.Get();
}
[Serializable]
public class UpdateLastNotifiedFilter : IBqlTable
{
#region DateNotified
public abstract class dateNotified : PX.Data.IBqlField
{
}
[PXDBDate()]
[PXDefault(typeof(AccessInfo.businessDate))]
[PXUIField(DisplayName = "Date Notified")]
public DateTime? DateNotified { get; set; }
#endregion
}
}
}
I get that exception when OrmLite make the following call :
return db.Select<T>(x => x.Name == name && x.PuId == puId).FirstOrDefault();
Exception :"System.Data.SqlClient.SqlException (0x80131904): The text,
ntext, and image data types cannot be compared or sorted, except when
usingIS NULL or LIKE operator.
The name is a String and puid is an Int. The type is mapped to a SQL Table which has no columns of type Text, NText or image at all.
When I look at the LastSQLStatement and executes it from SQL Server, it works. When I replace the call with the following, it works fine too
return db.SqlList<T>("SELECT Event_Id, Event_Num, Entry_On, Timestamp, Applied_Product, Source_Event, Event_Status, Confirmed, User_Id, Extended_Info, Comment_Id, PU_Id FROM Events WHERE ((Event_Num = #Event_Num) AND (PU_Id = #PU_Id))",new {Event_Num= "16J2730", PU_Id=91}).FirstOrDefault();
An old version of my service works fine with the same code. Using the latest version of servicestack and ormlite, I am now getting that weird issue...
Is the latest version of OrmLite has issues with old version of SQL Server? We are still on a 2000 version. I used both SQLServer Dialect without luck.
Anyone have an idea?
Here is what Mythz requested
public ProficyEvent TestGetByName(string name, int puId, bool withDetails = false)
{
using (IDbConnection db = OpenDBConnection())
{
try
{
return db.Select<ProficyEvent>(x => x.Name == name && x.PuId == puId).FirstOrDefault();
}
catch (Exception ex)
{
log.ErrorFormat("Error querying database: {0}", ex.ToString());
throw;
}
}
}
[Alias("Events")]
public class ProficyEvent:IProficyPuEntity
{
[AutoIncrement]
[Alias("Event_Id")]
public int Id { get; set; }
[Ignore]
public string Code { get; set; }
[Ignore]
public string Desc { get; set; }
[Alias("Event_Num")]
public string Name { get; set; }
[Alias("Entry_On")]
public DateTime? LastModified { get; set; }
[Ignore]
public string LastModifiedBy { get; set; }
public DateTime? Timestamp { get; set; }
[Alias("Applied_Product")]
public int? AppliedProductId { get; set; }
[Ignore]
public string AppliedProductName { get; set; }
[Ignore]
public int OriginalProductId { get; set; }
[Ignore]
public string OriginalProductName { get; set; }
[Alias("Source_Event")]
public int? SourceEvent { get; set; }
[Alias("Event_Status")]
public int? EventStatus { get; set; }
[Ignore]
public string EventStatusName { get; set; }
public int Confirmed { get; set; }
[Alias("User_Id")]
public int UserId { get; set; }
[Alias("Extended_Info")]
public string ExtendedInfo { get; set; }
[Ignore]
public string Comment { get; set; }
[Alias("Comment_Id")]
public int? CommentId { get; set; }
[Ignore]
public IEnumerable<ProficyTest> TestResults { get; set; }
[Alias("PU_Id")]
public int PuId { get; set; }
[Ignore]
public string UnitName { get; set; }
[Ignore]
public string LineName { get; set; }
}
CREATE TABLE [dbo].[Events](
[Event_Id] [int] IDENTITY(1,1) NOT NULL,
[Event_Num] [Varchar_Event_Number] NOT NULL,
[PU_Id] [int] NOT NULL,
[TimeStamp] [datetime] NOT NULL,
[Applied_Product] [int] NULL,
[Source_Event] [int] NULL,
[Event_Status] [tinyint] NULL,
[Confirmed] [bit] NOT NULL DEFAULT (0),
[User_Id] [int] NULL,
[Comment_Id] [int] NULL,
[Entry_On] [datetime] NULL,
[Testing_Status] [int] NULL DEFAULT (1),
[Event_Subtype_Id] [int] NULL,
[Start_Time] [Datetime_ComX] NULL,
[Extended_Info] [varchar](255) NULL,
[Converted_Timestamp] [datetime] NULL,
[Orientation_X] [float] NULL,
[Orientation_Y] [float] NULL,
[Orientation_Z] [float] NULL,
[Final_Dimension_Z] [real] NULL,
[Final_Dimension_A] [real] NULL,
[Initial_Dimension_A] [real] NULL,
[Final_Dimension_X] [real] NULL,
[Final_Dimension_Y] [real] NULL,
[Initial_Dimension_Y] [real] NULL,
[Initial_Dimension_Z] [real] NULL,
[Initial_Dimension_X] [real] NULL,
[Conformance] [tinyint] NULL,
[Testing_Prct_Complete] [tinyint] NULL)
CREATE TYPE [dbo].[Varchar_Event_Number] FROM [varchar](25) NOT NULL
CREATE TYPE [dbo].[Datetime_ComX] FROM [datetime] NOT NULL
To answer this question, this runs without issue on a recent version of SQL Server.
The major change to OrmLite that would have likely affected this behavior was the change to use Parameterized SQL Expressions from in-line SQL params.
You can use in-line SQL Params using OrmLite's legacy APIs or by dropping down to use Custom SQL APIs.
I am having below mentioned POCO classes.
public class AppointmentModel
{
public InvoiceDetail InvoiceDetails { get; set; }
public Invoice Invoice { get; set; }
}
public class InvoiceDetail
{
public Invoice Invoice { get; set; }
}
public class Invoice
{
public Invoice()
{
Id = Guid.NewGuid(); Created = DateTime.Now;
}
public Guid Id { get; set; }
public virtual Appointment Appointment { get; set; }
}
I have tried to add that model inside repository is as below.
public void Booking(AppointmentModel appointmentModel)
{
appointmentModel.InvoiceDetails.Invoice.LatestTotal = latestinvoiceTotal;
Catalog.Appointments.Add(appointmentModel.InvoiceDetails.Invoice.Appointment);
Catalog.SaveChanges();
}
It gives below mentioned error.
An entity object cannot be referenced by multiple instances of
IEntityChangeTracker
Stack Trace is as below.
at System.Data.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClass5.<Add>b__4()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at PawLoyalty.Data.PetBookings.Repositories.InvoiceRepository.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Data\PetBookings\Repositories\InvoiceRepository.cs:line 339
at PawLoyalty.Business.Invoices.InvoiceService.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Business\Invoices\InvoiceService.cs:line 38
at PawLoyalty.Business.BookingFacadeService.Booking(AppointmentModel appointmentModel) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Business\BookingFacadeService.cs:line 152
at PawLoyalty.Web.Controllers.PetBookingController.BookingProcess(String providerKey, String ownerKey, String serviceId, String petKeys, String selectedDates, String selectedExtraServices, String selectedResourceId, String key, String type) in d:\PawLoyalty Module\New Booking Flow\NewBookingFlow\PawLoyalty\PawLoyalty.Web\Controllers\PetBookingController.cs:line 243
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
UPDATE
It's coming through BasicRepository is as below.All repositories have been inherited from this.
public class BasicRepository : IBasicRepository
{
private DataCatalog catalog;
protected DataCatalog Catalog { get { if (catalog == null) catalog = new DataCatalog(); return catalog; } }
public void Dispose() { if (catalog != null) catalog.Dispose(); }
}
Can I have any help ?
I am creating this model as part of my code first entity framework
public class NewUserRegistration
{
[Key]
public int NewUserRegistrationId { get; set; }
}
Using the Update-Database -Verbose -Force command in the Package Manger ConsoleI get this exception during the this bit of the update Applying automatic migration: 201211252223088_AutomaticMigration.
ALTER TABLE [dbo].[NewUserRegistration] ADD [NewUserRegistrationId]
[int] NOT NULL IDENTITY System.Data.SqlClient.SqlException
(0x80131904): Multiple identity columns specified for table
'NewUserRegistration'. Only one identity column per table is allowed.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
methodName, Boolean async, Int32 timeout) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction
transaction, MigrationStatement migrationStatement) at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction
transaction, MigrationStatement migrationStatement) at
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1
migrationStatements) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable1
migrationStatements) at
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String
migrationId, XDocument targetModel, IEnumerable1 operations, Boolean
downgrading, Boolean auto) at
System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String
migrationId, XDocument sourceModel, XDocument targetModel, Boolean
downgrading) at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String
migrationId, XDocument sourceModel, XDocument targetModel, Boolean
downgrading) at
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at
System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable1
pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.Update(String
targetMigration) at
System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String
targetMigration) at
System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:a39395da-5f2b-48e0-bdac-b48d75a68c68 Multiple
identity columns specified for table 'NewUserRegistration'. Only one
identity column per table is allowed.
There is plainly only one Identity Column specified. So why is this the case?
When I do this I get no exception.
public class NewUserRegistration
{
[Key]
public int Id { get; set; }
}
Any thoughts on why this is the case?
EDIT
I should say that I am changing the name of the key. The comments say that you can't just do this. How can I drop and recreate?
Is it best to delete the database from SQL and then just run the Update-Database command again?
I encountered the same error when trying to rename a Key column. To make the migration work, I had to reorder the order of operations in my scaffolded migration script.
Here, I made sure to order the Drop operations first, then added the new Key field afterwards.
public partial class RenameKey : DbMigration
{
public override void Up()
{
DropPrimaryKey("dbo.GameSummary", new[] { "OldId" });
DropColumn("dbo.GameSummary", "OldId");
AddColumn("dbo.GameSummary", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.GameSummary", "Id");
}
I also didn't have any problem simply replacing the relevant DropPrimaryKey, DropColumn, AddColumn and AddPrimaryKey commands with a RenameColumn command, e.g.
public partial class RenameKey : DbMigration
{
public override void Up()
{
RenameColumn("dbo.GameSummary", "OldId", "Id");
}
}
I also had a similar problem after my first migrations. What I realized was that after I deleted the database which the first migration created and then too removed the migrations folder created in my mvc application, the problem did not appear again.
first Add-Migration -Name
then
public override void Up()
{
RenameColumn("dbo.Department", "OldId", "NewId");
}
You can just change the name of the column directly from the class using something like this:
[Column("ProductID")]
Example:
namespace Z_Market.Models
{
public class Product
{
[Key, Column("ProductID")] //This change the name of the column when you are using migration. If you have a form created already, you have to change the connection in the for to aim the new column name.
public int ID { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public DateTime LastBuy { get; set; }
public float Stock { get; set; }
public string remarks { get; set; }
public string deleteme { get; set; }
public ICollection<SupplierProduct> SupplierProducts { get; set; }
}
}
The best implementatios was:
/*Replace*/
DropPrimaryKey("dbo.GameSummary", new[] { "OldId" });
DropColumn("dbo.GameSummary", "OldId");
AddColumn("dbo.GameSummary", "Id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.GameSummary", "Id");
/*For*/
RenameColumn("dbo.GameSummary", "OldId", "Id");