How to set DBNull for decimal? - decimal

public class LoadTagMapModel
{
public string TAG { get; set; }
public string LOAD_CODE { get; set; }
public string SPEC_DATA { get; set; }
public string TAG_ID { get; set; }
public decimal? REF_VAL { get; set; }
public decimal? USL_VAL { get; set; }
public decimal? LSL_VAL { get; set; }
public int ORDER_NO { get; set; }
}
LoadTagMapModel model = new LoadTagMapModel
{
TAG = txtTag.Text,
LOAD_CODE = txtLOAD_CODE.Text,
TAG_ID = bteTAG_ID.Text,
SPEC_DATA = txtSPEC_DATA.Text,
REF_VAL = txtREF_VAL.Text == "" ? (decimal?)null : txtREF_VAL.Text.ToDecimal(),
USL_VAL = txtUSL_VAL.Text == "" ? (decimal?)null : txtUSL_VAL.Text.ToDecimal(),
LSL_VAL = txtLSL_VAL.Text == "" ? (decimal?)null : txtLSL_VAL.Text.ToDecimal(),
ORDER_NO = txtORDER_NO.Text.ToInt()
};
bool result = this.SaveData(model);
if (result)
{
this.MessageBoxShow("Saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
Search_Master();
return true;
}
I set types REF_VAL, USL_VAL, LSL_VAL to decimal?.
But if those value is null then in database it has to be DBNull value.
I want to these value can set DBNull value for decimal?.
Originally decimal couldn't allow null value but (decimal?)null is available.
In database, it has to be DBNull value type.
Could you help me?

Related

Selecting OrmLite new object from joined table for insertion

I have 3 entities:
[CompositeIndex(nameof(Url), nameof(TargetDomainRecordId), nameof(UserAuthCustomId), Unique = true)]
public class WatchedUrlRecord
{
[AutoIncrement]
public long Id { get; set; }
public string Url { get; set; }
public string Provider { get; set; }
public string DomainKey { get; set; }
public WatchedUrlScanStatus WatchedUrlScanStatus { get; set; }
public bool NoFollow { get; set; }
public HttpStatusCode HttpStatusCode { get; set; }
public DateTime? LastScanTime { get; set; }
public WatchedUrlScanResult LastScanData { get; set; }
public string Anchors { get; set; }
public int? OutboundLinks { get; set; }
[ForeignKey(typeof(TargetDomainRecord), OnDelete = "CASCADE")]
public long TargetDomainRecordId { get; set; }
[ForeignKey(typeof(UserAuthCustom), OnDelete = "CASCADE")]
public long UserAuthCustomId { get; set; }
}
[CompositeIndex(nameof(Url), nameof(TargetDomainRecordId), nameof(UserAuthCustomId), Unique = true)]
public class WatchedUrlQueue
{
[PrimaryKey]
public long WatchedUrlRecordId { get; set; }
[Index]
public string Url { get; set; }
[Index]
public string DomainKey { get; set; }
[Index]
public long TargetDomainRecordId { get; set; }
public string TargetDomainKey { get; set; }
[Index]
public DateTime CreateDate { get; set; } = DateTime.UtcNow;
public int Tries { get; set; }
[Index]
public DateTime? DeferUntil { get; set; }
[Index]
public long UserAuthCustomId { get; set; }
[Index]
public bool FirstScan { get; set; }
}
[CompositeIndex(nameof(Url), nameof(UserAuthCustomId), Unique = true)]
public class TargetDomainRecord
{
[AutoIncrement]
public long Id { get; set; }
public string Url { get; set; }
public string DomainKey { get; set; }
public DateTime CreateDate { get; set; } = DateTime.Now;
public DateTime? DeleteDate { get; set; }
public bool IsDeleted { get; set; }
public bool Active { get; set; } = true;
public DomainType DomainType { get; set; }
[ForeignKey(typeof(UserAuthCustom), OnDelete = "CASCADE")]
public long UserAuthCustomId { get; set; }
}
I am trying to insert queue objects based on IDs of WatchedUrlRecords so I came up with this query:
var q = db.From<WatchedUrlRecord>()
.Where(x => Sql.In(x.Id, ids))
.Join<TargetDomainRecord>((w, t) => w.TargetDomainRecordId == t.Id)
.Select<WatchedUrlRecord, TargetDomainRecord>((w, t) => new WatchedUrlQueue()
{
UserAuthCustomId = w.UserAuthCustomId,
DomainKey = w.DomainKey,
CreateDate = DateTime.UtcNow,
DeferUntil = null,
FirstScan = firstScan,
TargetDomainKey = t.DomainKey,
Tries = 0,
TargetDomainRecordId = w.TargetDomainRecordId,
Url = w.Url,
WatchedUrlRecordId = w.Id
});
var inserted = db.InsertIntoSelect<WatchedUrlQueue>(q, dbCmd => dbCmd.OnConflictIgnore());
This doesn't work and gives error:
variable 'w' of type 'Project.ServiceModel.WatchedUrl.Entities.WatchedUrlRecord' referenced from scope '', but it is not defined
If I try anonymous object like new {} instead of new WatchedUrlQueue then InsertIntoSelect() throws error:
'watched_url_record"."user_auth_custom_id' is not a property of 'WatchedUrlQueue'
I have looked in documentation and can see SelectMulti() method but I don't think that is suitable as it will involve me creating a tuple list to combine into the new object. The passed list can be quite large so I just want to send the correct SQL statement to PostgreSQL which would be along lines of:
insert into watched_url_queue (watched_url_record_id, url, domain_key, target_domain_record_id, target_domain_key, create_date, tries, defer_until, user_auth_custom_id)
select wur.id watched_url_record_id,
wur.url url,
wur.domain_key,
wur.target_domain_record_id,
tdr.domain_key,
'{DateTime.UtcNow:MM/dd/yyyy H:mm:ss zzz}' create_date,
0 tries,
null defer_until,
wur.user_auth_custom_id
from watched_url_record wur
join target_domain_record tdr on wur.target_domain_record_id = tdr.id
where wur.id in (323,3213123,312312,356456)
on conflict do nothing ;
I currently have a lot of similar type queries in my app and it is causing extra work maintaining them, would be really nice to be able to have them use fluent api without reducing performance. Is this possible?
Custom select expression can't be a typed projection (i.e. x => new MyType { ... }), i.e. you'd need to use an anonymous type expression (i.e. new { ... }) which captures your query's Custom SELECT Projection Expression.
You'll also need to put your JOIN expressions directly after FROM (as done in SQL) which tells OrmLite it needs to fully qualify subsequent column expressions like Id which would otherwise be ambiguous.
I've resolved an issue with field resolution of custom select expressions in this commit where your query should now work as expected:
var q = db.From<WatchedUrlRecord>()
.Join<TargetDomainRecord>((w, t) => w.TargetDomainRecordId == t.Id)
.Where(x => Sql.In(x.Id, ids))
.Select<WatchedUrlRecord, TargetDomainRecord>((w, t) => new {
UserAuthCustomId = w.UserAuthCustomId,
DomainKey = w.DomainKey,
CreateDate = DateTime.UtcNow,
DeferUntil = (DateTime?) null,
FirstScan = firstScan,
TargetDomainKey = t.DomainKey,
Tries = 0,
TargetDomainRecordId = w.TargetDomainRecordId,
Url = w.Url,
WatchedUrlRecordId = w.Id
});
var inserted = db.InsertIntoSelect<WatchedUrlQueue>(q, dbCmd=>dbCmd.OnConflictIgnore());
This change is available from v5.10.5 that's now available on MyGet.

MVC inserting values into a ViewModel after Model to ViewModel mapping

I am working with two different databases. I am passing the Model collection (SQL Server) to a ViewModel collection. The ViewModel has extra properties which I access out of a Visual Fox Pro database. I am able to map the existing properties, but the ViewModel does not save the data after passing the values to it.
The WoCust and the Lname fields return null, but the rest of the properties which come from the original Model pass to the properties in the ViewModel fine.
When I debug at the rdr for the OleDbCommand, it shows that the ViewModel is receiving a value for both rdr[WoCust] and rdr[Lname].
How do I make it so the ViewModel saves the new values?
WOSchedule.cs...
public partial class WOSchedule
{
public long Id { get; set; }
public string WoNo { get; set; }
public Nullable<long> QuoteTypeId { get; set; }
public Nullable<int> PriorityNo { get; set; }
public bool Active { get; set; }
public Nullable<System.DateTime> WoDate { get; set; }
public Nullable<long> QuoteID { get; set; }
public Nullable<System.DateTime> WoDone { get; set; }
public Nullable<long> WOScheduleListId { get; set; }
public string StorageLocation { get; set; }
public virtual QuoteType QuoteType { get; set; }
public virtual Quote Quote { get; set; }
public virtual WOScheduleList WOScheduleList { get; set; }
}
WoWcheduleVM.cs...
public partial class WoScheduleVM
{
public long Id { get; set; }
public string WoNo { get; set; }
public Nullable<long> QuoteTypeId { get; set; }
public Nullable<int> PriorityNo { get; set; }
public bool Active { get; set; }
public DateTime? WoDate { get; set; }
public Nullable<long> QuoteID { get; set; }
public DateTime? WoDone { get; set; }
public Nullable<long> WOScheduleListId { get; set; }
public string StorageLocation { get; set; }
public string WoCust { get; set; } // extra property
public string Lname { get; set; } // extra property
public virtual QuoteType QuoteType { get; set; }
public virtual Quote Quote { get; set; }
public virtual WOScheduleList WOScheduleList { get; set; }
}
WOSchedulesController.cs
string cs = ConfigurationManager.ConnectionStrings["foxproTables"].ConnectionString;
OleDbConnection cn = new OleDbConnection(cs);
var wOSchedules = db.WOSchedules.Where(w => w.WoDone == null).Include(w => w.QuoteType);
var wOSchedulesVM = wOSchedules.Select(s => new ViewModels.WoScheduleVM()
{
Id = s.Id,
WoNo = s.WoNo,
QuoteTypeId = s.QuoteTypeId,
PriorityNo = s.PriorityNo,
Active = s.Active,
WoDate = s.WoDate,
QuoteID = s.QuoteID,
WoDone = s.WoDone,
WOScheduleListId = s.WOScheduleListId,
StorageLocation = s.StorageLocation
});
cn.Open();
foreach (var sch in wOSchedulesVM)
{
string conn = #"SELECT wo_cust, lname FROM womast INNER JOIN custmast ON womast.wo_cust = custmast.cust_id WHERE wo_no = '" + sch.WoNo + "'";
OleDbCommand cmdWO = new OleDbCommand(conn, cn);
OleDbDataReader rdr = cmdWO.ExecuteReader();
while (rdr.Read())
{
sch.WoCust = ((string)rdr["wo_cust"]).Trim();
sch.Lname = ((string)rdr["lname"]).Trim();
}
}
cn.Close();
return View(wOSchedulesVM.OrderByDescending(d => d.WoDate).ToList());
The problem is you're using foreach loop for iterating wOSchedulesVM collection, which renders the source collection immutable during iteration. The older documentation version explicitly explains that behavior:
The foreach statement is used to iterate through the collection to get
the information that you want, but can not be used to add or remove
items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
Therefore, you should use for loop to be able to modify property values inside that collection, as shown in example below:
using (var OleDbConnection cn = new OleDbConnection(cs))
{
cn.Open();
string cmd = #"SELECT wo_cust, lname FROM womast INNER JOIN custmast ON womast.wo_cust = custmast.cust_id WHERE wo_no = #WoNo";
// not sure if it's 'Count' property or 'Count()' method, depending on collection type
for (int i = 0; i < wOSchedulesVM.Count; i++)
{
var sch = wOSchedulesVM[i];
using (OleDbCommand cmdWO = new OleDbCommand(conn, cn))
{
cmd.Parameters.AddWithValue("#WoNo", sch.WoNo)
OleDbDataReader rdr = cmdWO.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
sch.WoCust = (!rdr.IsDbNull(0)) ? rdr.GetString(0).Trim() : string.Empty;
sch.Lname = (!rdr.IsDbNull(1)) ? rdr.GetString(1).Trim() : string.Empty;
}
}
}
}
}
Note: This example includes 3 additional aspects, i.e. parameterized query, checking row existence with HasRows property and checking against DBNull.Value with IsDbNull().
Related issue: What is the best way to modify a list in a 'foreach' loop?

How to perform a more complex query with AutoQuery

Given the following definitions from a ServiceStack endpoint:
public class LoanQueue
{
public int LoanId { get; set; }
public DateTime Submitted { get; set; }
public DateTime Funded { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Fico { get; set; }
public int Fraud { get; set; }
public int CDS { get; set; }
public int IDA { get; set; }
public string Income { get; set; }
public string Liabilities { get; set; }
public string Agent { get; set; }
public string Status { get; set; }
public string State { get; set; }
public string Product { get; set; }
public string Comment { get; set; }
}
public enum DateType
{
None,
Submitted,
Funded
}
[Route("/loan/queue/search", "GET")]
public class LoanQueueQueryGet : QueryBase<LoanQueue>
{
public DateType DateType { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string AgentUserName { get; set; }
public Languange Languange { get; set; }
public bool WorkingLoan { get; set; }
public bool MicrobusinessLoan { get; set; }
public LoanStatus LoanStatus { get; set; }
}
public object Get(LoanQueueQueryGet request)
{
if (request == null) throw new ArgumentNullException("request");
var profiler = Profiler.Current;
using (profiler.Step("LoanServices.LoanQueue"))
{
SqlExpression<LoanQueue> q = AutoQuery.CreateQuery(request, Request.GetRequestParams());
QueryResponse<LoanQueue> loanQueueResponse = AutoQuery.Execute(request, q);
return loanQueueResponse;
}
}
My question is this, "Is it even possible to run conditional logic based on the request object in the service impl"? e.g.
If DateType == DateType.Submitted
then query the Submitted property on the LoanQueue with a BETWEEN clause (StartDate/EndDate) or
If DateType == DateType.Funded
then query the Funded property on the LoanQueue with a BETWEEN clause (StartDate/EndDate).
My guess is that I'm trying to bend AutoQuery too far and would be better served just coding it up the old fashion way. I really like the baked-in features of the AutoQuery plugin and I'm sure there will be times when it will suit my needs.
Thank you,
Stephen
AutoQuery will ignore any unmatched fields so you're able to use them to extend your populated AutoQuery with additional custom logic, e.g:
public object Get(LoanQueueQueryGet request)
{
var q = AutoQuery.CreateQuery(request, Request.GetRequestParams());
if (request.DateType == DateType.Submitted)
{
q.And(x => x.Submitted >= request.StartDate && x.Submitted < request.EndDate);
}
else
{
q.And(x => x.Funded >= request.StartDate && x.Funded < request.EndDate);
}
var loanQueueResponse = AutoQuery.Execute(request, q);
return loanQueueResponse;
}

assigning dates to entity fields during linq selects

I'm have a domain service for a LS application that selects rows and many of the fields in the row are datetime fields. I keep getting Linq to Entity errors about the date time conversion when I try to do the following code:
public IQueryable<riaProjectItem> FilterProjectItems(int? projID)
{
var FilteredProjectItems = _
from pi in this.Context.ProjectItems
where (pi.Project.Id == projID)
orderby pi.ItemCode ascending
select new riaProjectItem
{
// Note we turn the ID of the Internal Products to
// A negative number so we don't have duplicates
// with the External products
Id = pi.Id,
ItemCode = pi.ItemCode,
ItemName = pi.ItemName,
TechnicalStartDate = pi.TechnicalStartDate.GetValueOrDefault().Date,
TechnicalWeeks = Convert.ToDecimal(pi.TechnicalWeeks.ToString()),
TechnicalPercentComplete = Convert.ToDecimal(pi.TechnicalPercentComplete.ToString()),
EditingStartProjected = pi.EditingStartProjected.GetValueOrDefault().Date,
EditingStartActual = pi.EditingStartActual.GetValueOrDefault().Date,
EditingWordWeeks = Convert.ToDecimal(pi.EditingWordWeeks.ToString()),
EditingEditPercent = Convert.ToDecimal(pi.EditingEditPercent.ToString()),
EditingReview = Convert.ToDecimal(pi.EditingReview.ToString()),
ClientReviewStartProjected = pi.ClientReviewStartProjected.GetValueOrDefault().Date,
ClientReviewStartActual = pi.ClientReviewStartActual.GetValueOrDefault().Date,
TranslationPercent = Convert.ToDecimal(pi.TranslationPercent.ToString()),
ClientReview = Convert.ToDecimal(pi.ClientReview.ToString()),
FinalStartProjected = pi.FinalStartProjected.GetValueOrDefault().Date,
FinalStartActual = pi.FinalStartActual.GetValueOrDefault().Date,
FinalForm = Convert.ToDecimal(pi.FinalForm.ToString()),
FinalReview = Convert.ToDecimal(pi.FinalReview.ToString()),
CBTStartDateProjected = pi.CBTStartDateProjected.GetValueOrDefault().Date,
CBTStartDateActual = pi.CBTStartDateActual.GetValueOrDefault().Date,
CBTWeeks = Convert.ToDecimal(pi.CBTWeeks.ToString()),
CBTPercent = Convert.ToDecimal(pi.CBTPercent.ToString()),
DeliveryDate = pi.DeliveryDate.GetValueOrDefault().Date,
ActualDeliveryDate = pi.ActualDeliveryDate.GetValueOrDefault().Date,
Comments = pi.Comments
} ;
return FilteredProjectItems;
}
// Override the Count method in order for paging to work correctly
protected override int Count<T>(IQueryable<T> query)
{
return query.Count();
}
}
Class riaProjectItem
public class riaProjectItem
{
[Key]
public int Id { get; set; }
public int ItemCode { get; set; }
public string ItemName { get; set; }
public DateTime TechnicalStartDate { get; set; }
public Decimal TechnicalWeeks { get; set; }
public decimal TechnicalPercentComplete { get; set; }
public DateTime EditingStartProjected { get; set; }
public DateTime EditingStartActual { get; set; }
public decimal EditingWordWeeks { get; set; }
public decimal EditingEditPercent { get; set; }
public decimal EditingReview { get; set; }
public DateTime ClientReviewStartProjected { get; set; }
public DateTime ClientReviewStartActual { get; set; }
public decimal TranslationPercent { get; set; }
public decimal ClientReview { get; set; }
public DateTime FinalStartProjected { get; set; }
public DateTime FinalStartActual { get; set; }
public decimal FinalForm { get; set; }
public decimal FinalReview { get; set; }
public DateTime CBTStartDateProjected { get; set; }
public DateTime CBTStartDateActual { get; set; }
public decimal CBTWeeks { get; set; }
public decimal CBTPercent { get; set; }
public DateTime DeliveryDate { get; set; }
public DateTime ActualDeliveryDate { get; set; }
public string Comments { get; set; }
}
How do I assign dates to the entity fields?
When I assign the field I do so like this:
TechnicalStartDate = (pi.TechnicalStartDate.HasValue) ? pi.TechnicalStartDate.Value : (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue
You need to be clear you're using the SQL version of Min value and not the .NET value which is different.

entity framework looking in different table during unittests

I have a single DbContext in a library along with entities and their configuration in fluent api.
I use this same context in two different projects.
The first one is a test project and the second one a simple console application.
I execute a query including some of it's relations like this:
var vacancies = (from v in ctx.Vacancies
.Include("Categories")
.Include("Levels")
.Include("Contracts")
.Include("JobTypes"));
Strangely enough the console application works perfectly, however the unittest starts looking in the wrong tables all of a sudden.
Both applications produce very different queries when i look at them.
I'm using EF5 atm and I've been stuck on this for a few days now with not a single clue to what might cause this problem.
EDIT:
The point is i don't do any different queries, i also only have on context and only one connectionstring which i have confirmed during runtime connects to the right database.
All i can say is that i feel like the fluent api has no effect in unittests even though it hits the code just fine like it should.
public class SchedulerContext : BaseContext<SchedulerContext>{
public DbSet<Click> Clicks { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<ContractType> Contracts { get; set; }
public DbSet<JobType> JobTypes { get; set; }
public DbSet<Level> Levels { get; set; }
public DbSet<ExternalMapping> ExternalMappings { get; set; }
public DbSet<GeoName> GeoNames { get; set; }
public DbSet<GeoAlternateName> GeoAlternateNames { get; set; }
public DbSet<Trigger> JobTriggers { get; set; }
public DbSet<RegistryValue> RegistryValues { get; set; }
public DbSet<JobResult> JobResults { get; set; }
public DbSet<JobInfo> JobInfo { get; set; }
public DbSet<JobError> JobErrors { get; set; }
public DbSet<JobNotification> JobNotifications { get; set; }
public DbSet<Company> Customers { get; set; }
public DbSet<Vacancy> Vacancies { get; set; }
public SchedulerContext() {
//this.Configuration.ProxyCreationEnabled = false;
//this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Configurations.Add(new VacancyEntityTypeConfiguration());
base.OnModelCreating(modelBuilder);
}
}
That is my context.
And my entity configuration:
public class VacancyEntityTypeConfiguration : EntityTypeConfiguration<Vacancy> {
public VacancyEntityTypeConfiguration() {
this.HasMany(c => c.Levels).
WithMany().
Map(
m => {
m.ToTable("VacancyLevels");
});
this.HasMany(c => c.Categories).
WithMany().
Map(
m => {
m.ToTable("VacancyCategories");
});
this.HasMany(c => c.Contracts).
WithMany().
Map(
m => {
m.ToTable("VacancyContractTypes");
});
this.HasMany(c => c.Jobtypes).
WithMany().
Map(
m => {
m.ToTable("VacancyJobTypes");
});
}
}
And the exact method which shows the problem.
public List<Vacancy> GetVacanciesForCustomer(Company customer, bool onlineInclusive) {
using (var ctx = new JHSchedulerContext.SchedulerContext()) {
var vacancies = (from v in ctx.Vacancies.Include("Categories").Include("Levels").Include("Contracts").Include("JobTypes") where v.SourceSite == customer.SourceSite && (v.Online || onlineInclusive == false) select v).ToList();
return vacancies.ToList();
}
}
And the Vacancy class:
public class Vacancy {
public Vacancy()
{
this.Language = "";
}
[SolrUniqueKey("id")]
[Key]
[Required]
public int Id { get; set; }
[StringLength(50, ErrorMessage = "Maximum length 50 characters")]
public string ExternalId { get; set; }
[SolrField("title")]
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string Title { get; set; }
[SolrField("company")]
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string Company { get; set; }
[StringLength(4096, ErrorMessage = "Maximum length 4096 characters")]
public string CompanyText { get; set; }
[SolrField("location")]
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string Location { get; set; }
[SolrField("url")]
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string Url { get; set;}
[SolrField("source")]
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string SourceSite { get; set; }
private string text;
[SolrField("text")]
[StringLength(4096, ErrorMessage = "Maximum length 4096 characters")]
public string Text {
get {
return StringHelper.TruncateAtWord(text, 500);
//return new String(text.Take(500).ToArray());
//return text.Substring(text.Length < 900 ? 0 : (text.Length / 2), (int)Math.Min(text.Length, 500));
}
set{
text = value;
}
}
[StringLength(4096, ErrorMessage = "Maximum length 4096 characters")]
public string TextProfile { get; set; }
[StringLength(4096, ErrorMessage = "Maximum length 4096 characters")]
public string TextOffer { get; set; }
[NotMapped]
[ScriptIgnore]
public SqlGeography Coordinate {
get
{
if (Latitude.HasValue && Longitude.HasValue)
return SqlGeography.Point(Latitude.Value, Longitude.Value, 4326);
else
return null;
}
}
[SolrField("coordinate_0_coordinate")]
public double? Latitude { get; set; }
[SolrField("coordinate_1_coordinate")]
public double? Longitude { get; set; }
[StringLength(1024, ErrorMessage = "Maximum length 1024 characters")]
public string NormalizedLocation { get; set; }
public DateTime? ScrapedDate { get; set; }
[SolrField("insertdate")]
public DateTime? ImportDate { get; set; }
public DateTime? ExpireDate { get; set; }
[NotMapped]
public string DaysAgo {
get {
if (ImportDate != null)
return (DateTime.Now - (DateTime)ImportDate).Days.ToString();
else {
return "N/A";
}
}
}
[SolrField("category")]
public ICollection<string> CategoryNames {
get { return Categories != null ? Categories.Select(c => c.Name).ToList() : null; }
}
[SolrField("level")]
public ICollection<string> LevelNames {
get { return Levels != null ? Levels.Select(l => l.Name).ToList() : null; }
}
[SolrField("contract")]
public ICollection<string> ContractNames {
get { return Contracts != null ? Contracts.Select(c => c.Name).ToList() : null; }
}
[SolrField("time")]
public ICollection<string> JobTypeNames {
get { return Jobtypes != null ? Jobtypes.Select(c => c.Name).ToList() : null; }
}
public string ContactName { get; set; }
[Required]
public bool Online { get; set; }
[NotMapped]
public int? Distance { get; set; }
public string Language { get; set; }
public string PriorityType { get; set; }
public int NumClicks { get; set; }
[NotMapped]
public string GridContactName {
get{
return string.Format("{0} (Total Clicks:{1})",ContactName,NumClicks);
}
}
public virtual ICollection<Level> Levels { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<ContractType> Contracts { get; set; }
public virtual ICollection<JobType> Jobtypes { get; set; }
public override string ToString() {
return string.Format("Id={0} ExternalId={1} Title={2} Company={3} Location={4} Url={5} SourceSite={6} Text={7} NormalizedLocation={8} InsertDate={9} ImportDate={10} DaysAgo={11}",Id, ExternalId,Title,Company,Location,Url, SourceSite,Text,NormalizedLocation,ScrapedDate,ImportDate,DaysAgo);
}
}
And the Level class(all the other relation classes have the same structure(name,id):
public class Level {
[Key]
[Required]
public int Id { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Maximum length 100 characters")]
public string Name { get; set; }
public override string ToString() {
return string.Format("Id={0} Name={1}", Id, Name);
}
}
As far as connection to database goes you'll just have to believe me that i've checked both are connecting to the same database.(I even generated a new database with migrations enabled on this one since we use another context for migrations. That still had the exact same issue).
To clarify:
The unittest looks for table: CategoryVacancies.
The console application or even my windows service i use this in look for the right table: VacancyCategories.

Resources