Unknown Column In Field List - Field Does Not Exist on Entity - mysql

I'm having an issue figuring out where Entity Framework is getting the list of column names to query from a MySQL database. Essentially, when I am querying my context for a list of Discounts, a seemingly random property is getting attached, which doesn't exist in the database. I can't seem to find where, so I'm hoping someone has some troubleshooting guidance for me.
I have a Discount entity, that inherits off of my 'EntityBase' class.
public class Discount : EntityBase
{
public Discount(){}
}
public class EntityBase
{
public int Id { get; set; }
}
When I attempt to query discounts...
var discount = _myContext.Discounts.FirstOrDefault();
I get the following error - Unknown column 'd.AttendeeBadgeId' in 'field list'
Now, I DO have an AttendeeBadge entity, and I have a variety of other entities that utilize the AttendeeBadge. But I have absolutely nothing in the Discount class that utilizes the AttendeeBadge entity. I just have the Id property that gets inherited through EntityBase - and yet, my generated MySQL query is...
SELECT `d`.`Id`, `d`.`AttendeeBadgeId`
FROM `Discount` AS `d`
LIMIT 1
I've validated that in my modelBuilder for my context, I'm not mapping any particular properties that would cause an issue.
modelBuilder.Entity<Discount>().ToTable("Discount");
modelBuilder.Entity<Discount>().HasKey(_ => _.Id);
I thought something might be cached, but I've deleted all of the bin/obj folders for every single project in my solution, and I used Notepad++ to validate all of the areas that I reference the string value "AttendeeBadgeId", and I just get the other classes that reference it.
I'm at a loss here, would anyone know how I could see how the context is generating the SQL query in a more verbose way, or see where that column is coming from?

I should have tried harder before posting.
It turns out I had a property on the AttendeeBadge entity that had a list of Discounts.
public class AttendeeBadge : EntityBase
{
public AttendeeBadge ()
{
Discounts = new HashSet<Discount>();
}
public ICollection<Discount> Discounts { get; set; }
}
This was causing Entity Framework to assume there was a relationship between the Discount and the AttendeeBadge when I removed that dependency earlier today. I found out by copying the Discount class to another class, and then re-mapping my entities until I found the culprit causing my issue.

Related

EF 4.1 Code First doesn't create column for List<string>

I have been playing around quite a lot with EF4 Code First and I do love it. However, I cannot seem to sort this easy one out.
When trying to create something like this, no columns are created in my database:
public IList<String> Recievers { get; set; }
public List<String> RecieversTest { get; set; }
public virtual List<String> RecieversAnotherTest { get; set; }
public virtual ICollection<Int32> RecieversAnotherTest { get; set; }
Ive tried Annotations to map it to a different column name, I've tried IEnumerable and all sorts of other collections, but it refuses to create a column for it.
After an hour on google I found one that claims she has done it, but I'm starting to doubt that. Should it even be possible?
I can't really see why it just doesn't create a column and use JSON or CSV.
It can't be that rare, can it? In my case i just want to store a list of emails.
What am I missing? The project creates all other types without problems, and I've inspected the database to see how other properties I add to test with gets created, while these gets ignored.
So the problem must lie in some setting I'm missing or some configuration....
EF 4.1 RTW on an SQL Server 2008 db.
I have bad news for you. EF doesn't do anything like that. If you want any serialization and deserialization you must do it yourselves = you must expose and map property with serialized value:
private IList<String> _receivers;
// This will be skipped
public IList<String> Receivers
{
get
{
return _receivers;
}
set
{
_receivers = value;
}
}
// This will be mapped
public string ReceiversSer
{
get
{
return String.Join(";", _receivers);
}
set
{
_receivers = value.Split(';').ToList();
}
}
Now ReceiversSer will be mapped to a column in the database.
You can't have a column based on a collection/list of something. A column is a singular item such as public string Receiver.
If you are expecting EF CF to take your IList or List and make several Columns out of it you are correct in that it won't.
In EF CF you create lists in your Entity to represent a relationship to another table. An Order may have many Items in it. You would in this case have an Order class with a list to an OrderItem object.
You would then have an OrderItem class to describe the OrderItem table. This would then essentially represent the 1 to many relationship of Order and OrderItems.

PLINQO / LINQ-To-SQL - Generated Entity Self Save Method?

Hi I'm trying to create a basic data model / layer
The idea is to have:
Task task = TaskRepository.GetTask(2);
task.Description = "The task has changed";
task.Save();
Is this possible? I've tried the code below
Note: The TaskRepository.GetTask() methods detaches the Task entity.
I'd expect this to work, any ideas why it doesnt?
Thanks
public partial class Task
{
// Place custom code here.
public void Save()
{
using (TinyTaskDataContext db = new TinyTaskDataContext { Log = Console.Out })
{
db.Task.Attach(this);
db.SubmitChanges();
}
}
#region Metadata
// For more information about how to use the metadata class visit:
// http://www.plinqo.com/metadata.ashx
[CodeSmith.Data.Audit.Audit]
internal class Metadata
{
// WARNING: Only attributes inside of this class will be preserved.
public int TaskId { get; set; }
[Required]
public string Name { get; set; }
[Now(EntityState.New)]
[CodeSmith.Data.Audit.NotAudited]
public System.DateTime DateCreated { get; set; }
}
#endregion
}
Having done some reading I've realised I was implmenting the Repository pattern incorrectly. I should have been adding the Save method to the repository for conventions sake.
However, the actually problem I was having with regard to commiting the disconnected dataset was due to optimistic concurrency. The datacontext's job is to keep track of the state of it's entities. When entities become disconnected you loose that state.
I've found you need to add a timestamp field to the database table or I can set the UpdateCheck field on each column in my dbml file.
Here is some info about the UpdateCheck
Some useful links about disconnected Linq and plinqo
Great info on implementing the Repository pattern with LINQ
Short tutorial for implementing for updating and reattaching entities
Previously answer question
Rick Strahl on LINQ to SQL and attaching Entities
There is no need for this line (Task task = new Task();). The above should work although I've never seen it implemented in this manner. Have you thought about using the managers? Are you running into any runtime errors?
Thanks
-Blake Niemyjski

Linq - How to put common fields in a base class

I am trying to find a way so that I can push some common functionality into a base class for my Linq to SQL processing. I have two fields (ID and InsertUpdateOperID) that are common to most but not all of my tables. In my first go around I created a class called BaseEntity that had these fields. Unfortunately all I accomplished was hiding from the values in the .designer.cs file. I found an example of how to accomplish what I wanted In order to get around this (http://www.joe-stevens.com/2009/07/01/linq-to-sql-set-inheritance-modifiers-with-sqlmetal/). As per this article, I modifed the DBML file so that I could add the override modifier to the ID and InsertUpdateOperID properties on the tables that contained these two fields.
The net result of this was that the .designer.cs file added the override qualifier where I wanted it. This enabled me to create my BaseEntity class. Where I defined the ID field and the InsertUpdateOperID field as:
public virtual int ID { get; set; }
public virtual int InsertUpdateOperID { get; set; }
Doing this seemed to work fine.
The problem for me is that I hate the idea of modifying generated code. Can anyone suggest a way for me to put common fields and methods that act on those common fields in a base class so that I could accomplish what I want without modifying the generated .dbml?
Thanks
I'm facing the same problem today (wow, it's 1.5 years after your post), and struggled out a solution, so far it's good for me.
in the base class:
public virtual int __ID
{
get
{
PropertyInfo pi = this.GetType().GetProperty("ID");
int id = (int)pi.GetValue(this, new object[] {});
return id;
}
set
{
PropertyInfo pi = this.GetType().GetProperty("ID");
pi.SetValue(this, value, new object[] { });
}
}
This looks quite voilent, but it works!
Notice the __ before ID, because there is alread ID and _ID in the auto generated codes. As it's totally a new third way to access ID, no "override" is needed.
And if you need, you can use the __ID in or via your base class.

Saving and Retrieving Entities of different types using LINQtoSQL

Disclaimer: Bit of a C# newbie - first Software Dev gig in awhile after being in QA for a couple years.
I realize flavors of this question have been asked before (inheritance in LINQtoSQL and the like), but I'm hoping I ask the question differently.
In my database, I will have a super-type of "Event" and multiple sub-types: Conference, Meeting and Appointment, for example.
Event
Id (PK)
TypeId (FK EventTypes.Id)
Title
Conference
Id (PK, FK Event.Id)
Cost
Topic
Meeting
Id (PK, FK Event.Id)
Location
Organizer
Appointment
Id (PK, FK Event.Id)
Time
Address
I am using Rob Conery's MVC StoreFront application as a reference. He essentially gets data from the database and creates class objects, manually mapping Event.Id to db.Event.Id, etc.
I'd like to do this with my Events data model - I'd like to retrieve all Events, and have a LINQ expression dynamic enough to create various event types based on some criteria (TypeId, for example).
var result = from e in db.Events
select new IEvent
{
// Little help? ;)
};
It would be great to find a way to make it so each Event Type knows how to save itself and retrieve itself - I fear having to write the same code for each type, only varying the fields. Make sense?
I did see a question posed and someone answered with something like:
public bool Save<T>() {}
The problem is, I'm not sure where to put this code. I'm also not sure if I should use an IEvent interface or an Event partial class.
I will now end this monster question with an advanced Thank You to those that can offer help/suggestions.
--
EDIT: Good progress - going from DB to Views all with IEvent :) (This Question Helped A Lot)
public class SqlEventRepository : IEventRepository
public IQueryable<IEvent> getEvents() {
// Get Events without doing a query for each type..possible?
var eventType1 = {query};
var eventType2 = {query};
return {concat of all queries};
}
public bool SaveEvent(IEvent) {
// Can I avoid calling a save function for each type of event?
}
You could have a helper class to put your Save<T>() method in. Something like SaveEvents class.
When you want to save using LINQ I'm not so sure that you can use generics as you don't know what T is and therefore cannot update properties in your queries.
I'd use inheritance and then where you'd pass a sub-class, use the parent class (Event) as your argument. Then you can quite easily cast to your subclasses to access those properties in your LINQ Queries.
EDIT:
Something like this:
public class Event : IEvent (Interface implement common properties to all Event type classes)
{
// your code
}
public class MeetingEvent : IEvent
{
public string MeetingEvent
{
get;
set;
}
// add IEvent implementation...
}
public class EventManager
{
public void MyMethod (IEvent event)
{
MeetingEvent Mevent = (MeetingEvent)event;
Mevent.DoSomework();
// now you can cast all eventclasses to and from IEvent passed as a parameter.
}
}

Mapping a derived class to a table in Linq-to-SQL

I have an abstract base class for audit properties. For brevity say it has one property
Public MustInherit Class AbstractAuditableEntity
...
Public Property CreatedTime() As DateTimeOffset
...
End Class
And then my auditable domain objects inherit from this class
Public Class Source
Inherits AbstractAuditableEntity
...
Public Property SourceId() As String
...
End Class
I have the following table DDL to which I want to map my domain object "Source". Essentially the relationship between each (concrete) domain object and table is 1-1, with each table having the required audit column.
CREATE TABLE Source
(
SourceID VARCHAR(10) NOT NULL,
CreatedTime DATETIMEOFFSET(3) NOT NULL,
CONSTRAINT PK_Source PRIMARY KEY (SourceID))
GO
Using an external mapping file my first attempt to map the class to the table would foolishly be:
<?xml version="1.0" encoding="utf-8"?>
<Database Name="" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
<Table Name="Source" Member="Sources">
<Type Name ="Source">
<Column Name="SourceID" Member="SourceID" IsPrimaryKey="true" CanBeNull="false"/>
<Column Name="CreatedTime" Member="CreatedTime" />
</Type>
</Table>
</Database>
However this generates the following exception:
The column or association 'CreatedTime' in the mapping had no corresponding member in type 'Source'. Mapping members from above root type is not supported.
Within the context of my persistence layer I am not trying to represent an inheritance hierarchy as such, but within the context of my application I am simply using a base class to provided properties required by all my domain objects. With a lot of fiddling with my mapping file (including mapping the audit columns to the base AbstractAuditableEntity type) and reading around, I am unable to achieve what I perceive as quite a straighforward ORM task.
Any thoughts or suggestions would be most welcome!
Thanks
I'm guessing that you are trying to emulate auditing fields like Ruby on Rails updated_on, created_on. If so, here is how I accomplished something similar using this post as a starting point
http://weblogs.asp.net/stevesheldon/archive/2008/02/23/a-method-to-handle-audit-fields-using-linq-to-sql.aspx
I implemented an interface in the Models namespace like so:
public interface IAuditable
{
DateTime CreatedOn { get; set; }
string CreatedBy { get; set; }
DateTime? ChangedOn { get; set; }
string ChangedBy { get; set; }
}
And then extended the partial classes of the data entities that had these fields:
public partial class DataModelIWantToAudit : IAuditable
{
}
And then overrode SubmitChanges on the DataContext to check for the implementation of the interface with the magic of Linq OfType<>:
public override void SubmitChanges(ConflictMode failureMode)
{
//Updates
foreach (var updatedModel in GetChangeSet().Updates.OfType<IAuditable>())
{
updatedModel.ChangedOn = DateTime.Now;
updatedModel.ChangedBy = Membership.GetUser().UserName;
}
//Inserts
foreach (var insertedModel in GetChangeSet().Inserts.OfType<IAuditable>())
{
insertedModel.CreatedOn = DateTime.Now;
insertedModel.CreatedBy = Membership.GetUser().UserName;
}
base.SubmitChanges(failureMode);
}
Hope that helps!
-Kelly
Kelly showed a great sample of how to do it - but you've basically hit one of the limitations of Linq-to-SQL.
It works great if you database table map more or less 1:1 to your domain objects. But it's weak and causes a lot of extra work once this is no longer the case.
In such a case, as soon as you have domain object inheritance and other things that need to be mapped to database tables, you're best bet would be to check out ADO.NET Entity Framework instead. The EF is specifically designed to handle these things - if you ever think "I need to map my objects ......" then you should think EF! :-)
Granted, the current EF shipping in .NET 3.5 SP1 has its warts and annoyances, but the EF 4 that is part of the .NET 4.0 wave (which should ship before the end of this year 2009), should solve a great many of those warts!
Check out the ADO.NET Entity Framework team blog for some teasers of what EF4 will bring us all!
Marc