I have a view in my SQL database. All I want is to retrieve data from that view.
I have added POCO class.
namespace WFPersistence.DataModel
{
public class Instance
{
public Guid InstanceId { get; set; }
public DateTime? PendingTimer { get; set; }
public DateTime? CreationTime { get; set; }
public DateTime? LastUpdatedTime { get; set; }
public int? ServiceDeploymentId { get; set; }
public string SuspensionExceptionName { get; set; }
public string SuspensionReason { get; set; }
public string ActiveBookmarks { get; set; }
public string CurrentMachine { get; set; }
public string LastMachine { get; set; }
public string ExecutionStatus { get; set; }
public bool? IsInitialized { get; set; }
public bool? IsSuspended { get; set; }
public bool? IsCompleted { get; set; }
public byte? EncodingOption { get; set; }
public byte[] ReadWritePrimitiveDataProperties { get; set; }
public byte[] WriteOnlyPrimitiveDataProperties { get; set; }
public byte[] ReadWriteComplexDataProperties { get; set; }
public byte[] WriteOnlyComplexDataProperties { get; set; }
public string IdentityName { get; set; }
public string IdentityPackage { get; set; }
public long? Build { get; set; }
public long? Major { get; set; }
public long? Minor { get; set; }
public long? Revision { get; set; }
}
public class Instances : Collection<Instance>
{
}
}
This is how I am trying to map with view.
public class WFPersistenceStore : DbContext
{
public WFPersistenceStore() : base("WFPersist")
{
}
public DbSet<Instance> PersistedInstances { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Instance>().ToTable("System.Activities.DurableInstancing.Instances");
}
}
This is how I am connecting with view
using (var PersistStore = new WFPersistenceStore())
{
var result = from t in PersistStore.PersistedInstances
select t;
////
///
}
I am getting this error:
An unhandled exception of type 'System.ArgumentException' occurred in
RentalHost.exe
Additional information: The database name
'System.Activities.DurableInstancing.Instances' is invalid. Database
names must be of the form [.].
Your method should be like
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Instance>().ToTable("Instances");
}
I have resolved my issue by just putting the following line inside the constructor of my context class (i.e. WFPersistenceStore).
Database.SetInitializer<WFPersistenceStore>(null);
This wasn't mentioned anywhere clearly in official documents if i am not wrong.
The above line needed for EF6 version only but not required for earlier versions of EF.
Related
I have following two class structures, its CASADetialsResponse as follows,
public class CASADetialsResponse
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
And the CASADetails class structure as follows,
public class CASADetails
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
When I use _mapper.Map<CASADetialsResponse>(casaResponse); I'm getting this error:
Error mapping types:
Mapping types:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Type Map configuration:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Destination Member:
data
This is how I map the two classes,
public class CASADetailsProfile : Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
}
}
I just commented the public Data data { get; set; } from the both classes, and without any error its worked. I think problem is with that line. may I know the reason? please help me
The namespace for Data class is different, even though their content is the same.
Delete these
and refer to source Data class namespace or
If you don't want to delete them, add the following configuration
public class CASADetailsProfile: Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
CreateMap<Sources.Data, Destinations.Data>();
CreateMap<Sources.Account, Destinations.Account>();
CreateMap<Sources.Transaction, Destinations.Transaction>();
CreateMap<Sources.LinkedCard, Destinations.LinkedCard>();
CreateMap<Sources.JointParty, Destinations.JointParty>();
}
}
Change Sources namespace and Destinations namespace to the namespace that you have
I have a task which requires me to return all models from a table using inheritance (TPH).
I have a model class called WorkflowInstance and a derived class CustomWorkflowInstance (which has a string property). There is a discriminator of course.
I want to know of a way where I can return all the elements without considering the discriminator
public class WorkflowInstance : Entity, ITenantScope, ICorrelationScope
{
public WorkflowInstance();
public SimpleStack<ActivityScope> Scopes { get; set; }
public SimpleStack<ScheduledActivity> ScheduledActivities { get; set; }
public WorkflowFault? Fault { get; set; }
public HashSet<BlockingActivity> BlockingActivities { get; set; }
public IDictionary<string, IDictionary<string, object?>> ActivityData { get; set; }
public WorkflowOutputReference? Output { get; set; }
public WorkflowInputReference? Input { get; set; }
public Variables Variables { get; set; }
public Instant? FaultedAt { get; set; }
public Instant? CancelledAt { get; set; }
public Instant? FinishedAt { get; set; }
public Instant? LastExecutedAt { get; set; }
public Instant CreatedAt { get; set; }
public string? Name { get; set; }
public string? ContextId { get; set; }
public string? ContextType { get; set; }
public string CorrelationId { get; set; }
public WorkflowStatus WorkflowStatus { get; set; }
public int Version { get; set; }
public string? TenantId { get; set; }
public string DefinitionId { get; set; }
public ScheduledActivity? CurrentActivity { get; set; }
public string? LastExecutedActivityId { get; set; }
}
public class CustomWorkflowInstance : WorkflowInstance
{
public Guid UserId { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<WorkflowInstance>()
.HasDiscriminator<int>("Discriminator")
.HasValue(0)
.HasValue<WorkflowInstance>(0)
.HasValue<CustomWorkflowInstance>(1);}
I want to find a way to query the table as it is meaning adding where clause FinishedAt > etc (the issue is that UserId exist only in derived class but all the data is in base class where discriminator always equals 0)
so by doing select * from WorkflowInstanceTABLE where Used="xx" it automatically adds the where discriminator = 1 (because I wrote _dbContext.CustomWorkflowInstance which contains the userId in question.
I have the following two classes:
public class Record
{
public int RecordId { get; set; }
public DateTime? InsertDate { get; set; } = DateTime.Now;
public DateTime BookingDate { get; set; }
public string AmountTypeName { get; set; }
public double? Amount { get; set; }
public string BookingAccountID { get; set; }
public string AccountCurrency { get; set; }
public string ClientCurrency { get; set; }
public string AffectsBalance { get; set; }
public double? AmountAccountCurrency { get; set; }
public string AmountClientCurrency { get; set; }
public int UnifiedInstrumentCode { get; set; }
public InstrumentInfo InstrumentInfo { get; set; }
}
public class InstrumentInfo
{
[Key]
public int UnifiedInstrumentCode { get; set; }
public ICollection<Record> Record { get; set; }
public string AssetType { get; set; }
public int UnderlyingInstrumentUic { get; set; }
public string UnderlyingInstrumentSubType { get; set; }
public string InstrumentSymbol { get; set; }
public string InstrumentDescription { get; set; }
public string InstrumentSubType { get; set; }
public string UnderlyingInstrumentAssetType { get; set; }
public string UnderlyingInstrumentDescription { get; set; }
public string UnderlyingInstrumentSymbol { get; set; }
}
that I want to use as my context for EF6.
I defined the context the following way:
public class TransactionsContext: DbContext
{
public DbSet<Record> Records { get; set; }
public DbSet<InstrumentInfo> InstrumentInfos { get; set; }
public TransactionsContext()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<TransactionsContext>(null);
base.OnModelCreating(modelBuilder);
}
}
If I run a test against it that shall add and InstrumentInfo object to the DB
[TestMethod]
public void AddInstrumentInfo_Added_IsTrue()
{
InstrumentInfo info = FakeFactory.GetInstrumentInfo();
using (var ctx = new TransactionsContext())
{
ctx.InstrumentInfos.Add(info);
ctx.SaveChanges();
}
}
I get the following exception:
SqlException: Cannot insert the value NULL into column
'UnifiedInstrumentCode', table
'TransactionsContext.dbo.InstrumentInfoes'; column does not allow
nulls. INSERT fails. The statement has been terminated.
I tried all different scenarios that I found here but I couldn't figure out what I'm doing wrong.
The ultimate goal is that i define my two classes in a way so that a "Record" is linked to the "InstrumentInfo" table via the "UnifiedInstrumentCode" property.
My guess is that my constraints for this two tables are still not correct, but I cant figure out how to define it in EF6 (code first) to get this working.
Adding the annotation [DatabaseGenerated(DatabaseGeneratedOption.None)] to my primary key in InstrumentInfo solved the problem:
public class InstrumentInfo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UnifiedInstrumentCode { get; set; }
public ICollection<Record> Record { get; set; }
public string AssetType { get; set; }
public int UnderlyingInstrumentUic { get; set; }
public string UnderlyingInstrumentSubType { get; set; }
public string InstrumentSymbol { get; set; }
public string InstrumentDescription { get; set; }
public string InstrumentSubType { get; set; }
public string UnderlyingInstrumentAssetType { get; set; }
public string UnderlyingInstrumentDescription { get; set; }
public string UnderlyingInstrumentSymbol { get; set; }
}
I did not investigate further but my guess is that if a new Record is added, EF initially creates and InstrumentInfo object that has a Null Value for its Primary key which causes the Exception.
I hope it helps if somebody runs into the same problem in future.
in EF Codefirst there is a middle table(Model) in my project like `:
public class ClientDriverLoad
{
public ClientDriverLoad()
{
DateTime = DateTime.Now.Date;
}
public int Id { get; set; }
public virtual Client Client { get; set; }
public DateTime DateTime { get; set; }
public virtual List<DriverLoad> DriverLoads { get; set; }
public virtual User User { get; set; }
}
and Client that derives from it's parent Person:
public class Client:Person
{
public virtual List<ClientDriverPayment> ClientPayments { get; set; }
public virtual List<ClientDriverLoad> ClientDriverLoad { get; set; }
}
and DriverLoad Model is like this :
public class DriverLoad
{
public int Id { get; set; }
public virtual Driver Driver { get; set; }
public virtual Load Load { get; set; }
public string StartPoint { get; set; }
public string Destination { get; set; }
public long price { get; set; }
public virtual ClientDriverLoad ClientDriverLoad { get; set; }
}
and clientDriverPayment like this :
public class ClientDriverPayment
{
public ClientDriverPayment() {
DateTime = DateTime.Now.Date;
}
public int Id { get; set; }
public DateTime DateTime { get; set; }
public virtual Client Client { get; set; }
public virtual Driver Driver { get; set; }
public virtual Payment Payment { get; set; }
public virtual User User { get; set; }
}
if searched a lot and figured I should use Fluent Api or something how should I determine what relationship should I Use could anyone help me please ?
please use these codes in your DbContext class
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<ClientDriverLoad>().HasMany(m => m.DriverLoads).WithRequired(m => m.ClientDriverLoad);
mb.Entity<ClientDriverPayment>().HasRequired(m => m.Client).WithMany(m => m.ClientPayments);
}
I have the following 2 models:
public class Alert
{
public int Id { get; set; }
public DateTime AlertDatetime { get; set; }
public bool Unread { get; set; }
public int? ReadByUserId { get; set; }
public DateTime? ReadDateTime { get; set; }
public DateTime ImportDateTime { get; set; }
public bool AlertHasRecords { get; set; }
//Error Reporting and Recording.
public bool Error { get; set; }
public string ErrorText { get; set; }
public virtual IEnumerable<AlertRecord> Records { get; set; }
}
public class AlertRecord
{
public int Id { get; set; }
public string HospitalNumber { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime EventDateTime { get; set; }
public string CrisNumber { get; set; }
public DateTime CreationDateTime { get; set; }
//Link it back to the master Alert!
public int AlertId { get; set; }
public virtual Alert Alert { get; set; }
}
Once the "Alert" Object properties have values in them, I am trying to use EntityFramework to inset this object into my SQL DB like this:
class Program
{
private static Alert MainAlert = new Alert();
private static PrimaryDBContext db = new PrimaryDBContext();
static void Main(string[] args)
{
MainAlert = AlertObjectFactory.GetAlertObject();
db.Alerts.Add(MainAlert);
db.SaveChanges();
}
}
The AlertObjectFactory.cs and The Class responsible for building the list of AlertRecords are here(They are large class files)
https://gist.github.com/anonymous/67a2ae0192257ac51f39
The "Alert" Table is being populated with data, however the 4 records in the
IEnumerable Records
are not being inserted...
Is this functionality possible with EF?
Try changing your IEnumerable to something that implements ICollection such as List
See this answer for more details