I am trying to make One To Zero One association between two tables in Telerik Data Access, but can't make it work. Here are my tables:
Student
Id (PK)
Name (string)
BackPack
Id (PK)
StuffInside(string)
StudentId (Unique, Foreign key)
StudentId in Backpack references to Id in Student. When I do the mapping for some reason Telerik is making it One to Zero Many. I need One To Zero One.
I assume you are using the Telerik Data Access Visual Designer to model your database? If so, in order to create one-to-one association you need to specify that the ID from one table (Students) matches the ID from the other table (BackPacks). This way each student will have exactly one (or zero) backpack. Please refer to this documentation article which demonstrates the approach.
If this is not applicable in your scenario and you have to match the Student ID to the BackPack StudentId to achieve the same effect you could create one-to-many association and then manually create the unique constraint on the database server side. Alternatively you could switch to Fluent Mapping which allows you to create custom indexes in you mapping.
I am working on a C# project querying a Sql Db by the auto-generated classes by the sqlmetal tool. That works fine.
My problem is that in my DB I have to tables (TableA and TableB) which have a many to many relationship, therefore, there is a third table called TableATableB which holds only the primary keys of TableA and TableB.
So, as expected, my EntityModel has a class named TableA that has a property named TableATableB which is a collection of all related TableATableB rows.
That is the auto-generated property:
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="FK_TableATableB_TableA", Storage="_TableATableB", ThisKey="Id", OtherKey="TableAId", DeleteRule="CASCADE")]
public EntitySet<TableATableB> TableATableB
{
get
{
return this._TableATableB;
}
set
{
this._TableATableB.Assign(value);
}
}
The thing is I would like TableA to have a property named TableB which gives me directly an System.Data.EntitySet<TableB> collection of all related TableB rows, is there a way to do that? I have been trying to do it but I haven't found the way to map it.
Just to clarify, I know a workaround simply could be as follows, but I'm trying to see if there is a better way. Besides, this way how could I know when a TableB object is added to the collection in order to add the respective TableATableB object?
partial class TableA
{
public List<TableB> TableB
{
get
{
List<TableB> tableBRows = new List<TableB>();
foreach (TableATableB tAtB in this.TableATableB)
{
tableBRows.Add(tAtB.TableB);
}
return tableBRows;
}
set
{
// What to do here?
// I need to know when an element is added in order to add its respective
// TableATableB object
}
}
Thanks in advance.
Linq to SQL does not support the behavior you desire. L2S does not support implicit many-many collections like EF.
Entity Framework does, but requires that the all fields of the many-many table (TableATableB in your case) make up the primary key of that table. For example, if TableA's primary key is Id and TableB's primary key is Id then TableATableB must have exactly two fields, TableA_Id and TableB_Id, that are the primary key of that table. If TableATableB were to have three fields in this case like Id, TableA_Id and TableB_Id, and Id is the primary key of the many-many table then EF cannot and will not treat that as an implicit many-many collection.
The following are two partial tables in which I am trying to define a foreign key relationship.
public class Form
{
[Key, Column("FormID")]
public System.Guid FormGUID { get; set; }
[Column("PatGUID")]
public Nullable<System.Guid> PatientGUID { get; set; }
}
public class Patient
{
[Column("PatGUID")]
public System.Guid PatientGUID { get; set; }
[Key, Column("PatID")]
public int PatientID { get; set; }
}
I've eliminated all but the relevant information, fields, navigations, etc. for this example; hopefully not too much.
We have a table Form, with a FK of PatGUID to a Patient table with field PatGUID.
The Patient table has a PatID int KEY field.
We have requirements to rename our fields for our code first entity models; the relevant fields in this example needing changed is PatGUID being changed to PatientGUID.
The difficulty I am having is trying to define this foreign key using either annotations or fluent.
So the end result I need is:
Primary Key Table: Patient, Field: PatGUID (renamed PatientGUID)
Foreign Key Table: Form, Field: PatGUID (renamed PatientGUID)
This doesn’t seem like it should pose a large problem but with the combination of Patient.PatGUID not being the primary key and the PatGUID fields being renamed to PatientGUID has not enabled the WCF Data Service to properly create a reference with a proper reference thus a proper select/join of:
SELECT … FROM [dbo].[Form] AS [Extent1]
INNER JOIN [dbo].[Patient] AS [Extent2] ON [Extent1].[PatGUID] = [Extent2].[PatGUID]
EF doesn't yet support relationships where the principal's key is not the primary key but some other column with a unique key constraint. It is on the feature request list but neither implemented nor on the road map for the next release (EF 6). If it gets implemented at all (in EF 7 maybe) expect to wait a year or more until it's ready for production.
In your particular model EF doesn't recognize any relationship between Form and Patient at all because Patient.PatientID is marked as [Key], not Patient.PatientGUID, and EF treats Form.PatientGUID as an ordinary scalar property, not as an FK to Patient.
In theory you could fake Patient.PatientGUID as the [Key] property in the model although it is not the primary key in the database if you don't create the model from the database or the database from a code-first model, that is, if you map between model and (existing) database manually. But I am not sure if this wouldn't cause subtle problems anywhere else.
The alternative is to write manual join statements in LINQ if you want to fetch Patients and related Forms. You can then join two entities using arbitrary properties, not only key properties. This is, in my opinion, the cleaner and less "tricky" approach. However, the downside is that you won't have navigation properties - references or collections - between Patient and Form and you can't use features like eager loading (Include), lazy loading or comfortable "dotted path syntax" (like Form.Patient.SomePatientProperty, etc.) in your LINQ queries.
I get this error when writing to the database:
A dependent property in a ReferentialConstraint is mapped to a
store-generated column. Column: 'PaymentId'.
public bool PayForItem(int terminalId, double paymentAmount,
eNums.MasterCategoryEnum mastercategoryEnum, int CategoryId, int CategoryItemId)
{
using (var dbEntities = new DatabaseAccess.Schema.EntityModel())
{
int pinnumber = 0;
long pinid = 1; //getPinId(terminalId,ref pinnumber) ;
var payment = new DatabaseAccess.Schema.Payment();
payment.CategoryId = CategoryId;
payment.ItemCategoryId = CategoryItemId;
payment.PaymentAmount = (decimal)paymentAmount;
payment.TerminalId = terminalId;
payment.PinId = pinid;
payment.HSBCResponseCode = "";
payment.DateActivated = DateTime.Now;
payment.PaymentString = "Payment";
payment.PromotionalOfferId = 1;
payment.PaymentStatusId = (int)eNums.PaymentStatus.Paid;
//payment.PaymentId = 1;
dbEntities.AddToPayments(payment);
dbEntities.SaveChanges();
}
return true;
}
The schema is:
Is it possible that you defined a bad column relation between your tables?
In my case, I had different columns and one was set as autonumeric.
This error says that you are using unsupported relation or you have error in your mapping. Your code is most probably absolutely unrelated to the error.
The error means that you have some relation between entities where foreign key property in dependent entity is defined as store generated. Store generated properties are filled in the database. EF doesn't support store generated properties as foreign keys (as well as computed properties in primary keys).
I had the same problem. Based on the answers provided here I was able to track it and solve it, but I had a strange issue described below - it might help somebody in the future.
On my dependent tables, the foreign Key columns have been set to StoreGeneratedPattern="Identity". I had to change it to "None". Unfortunately, doing so inside designer didn't work at all.
I looked in the designer-generated XML (SSDL) and these properties were still there so I removed them manually. I also had to fix the columns on the database (remove the Identity(1,1) from CREATE TABLE SQL)
After that, the problem went away.
I had the same problem and after some digging in table design in sql server , I found that mistakenly i set table's primary key also as foreign key.
In this image you can see that JobID is table's primary key but also mistakenly foreign key.
My problem was caused by redundant defining of the Primary key in the configuration.
this
.Property(p => p.Id)
.HasColumnName(#"id")
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) // this is redundant when you want to configure a One-to-Zero-or-One relationship
.HasColumnType("int");
Remove this line
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
Example http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx
This is enough to define the relationship
// Configure Student & StudentAddress entity
modelBuilder.Entity<Student>()
.HasOptional(s => s.Address) // Mark Address property optional in Student entity
.WithRequired(ad => ad.Student); // mark Student property as required in StudentAddress entity. Cannot save StudentAddress without Student
Re-check the relationship between Payment and the other tables/entities. Including the ones that shouldn't contain PaymentId because that's where the problem is most likely hiding.
When creating foreign keys in SQL Server Management Studio, the primary key is defaulted, and this default is reverted when the parent table is changed, so be careful to change values in the correct order in the "Tables and Columns" window.
Also, after you've fixed the problematic relationship, there's a good chance that a simple "Refresh" on the model won't correctly remove the erronous relationship from the model and you'll get the same error even after the "fix", so do this yourself in the model before performing a refresh. (I found this out the hard way.)
If you have checked your relationships and are good there.
Delete the table in the edmx and then update from database. This will save you doing the update manually.
For me it was a wrongly placed foreign key in the table but even after altering the table to fix it, it was still not working. You need to update the EDMX files (and not enough to "refresh" the table from the model, you need to remove and add the table again in the model).
In addition to the accepted answer, if you are using EF Reverse POCO generator or some other tool that generates your POCO's, make sure you regenerate them!
In my case Id field wich FK just in Entity Framework the propierty "StoreGeneratedPattern" was set "Itentity" instead of "None"
In my case the problem was caused by having a two-way 1-1 relationship:
class Foo{
[Key]
Id
[ForeignKey]
BarId
...
}
class Bar{
[Key]
Id
[ForeignKey]
FooId
...
}
I had to simply remove one of the two foreign keys (not necessary anyway).
In my case it was simply that I did not have permissions set properly on the database. I had read only set and Entity framework was giving me a ReferentialConstraint error which threw me off. Added additional write permissions and all was well.
In my case, I had a Database Generated property, and a ForeignKey navigation property set up to reference a 1 to 1 related table.
This wasn't something I could remove, I needed to be able to both set the primary key of the entity to be Database Generated AND I needed to be able to reference the 1 to 1 table as a navigation property.
Not sure if this is the same for others, but this problem was only showing up when creating a new entity, reading or editing existing entities did not exhibit the issue, so I got around the issue by creating an inherited version of my Context and using the Fluent method to switch off the navigation property when creating.
So, my original entity looked like this:
public partial class MyEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid id{ get; set; }
// Navigation
[ForeignKey("id")]
public PathEntity Path { get; set; }
}
So I made a special inherited context that looked like this:
private class _navPropInhibitingContext : EF.ApplicationDBContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>()
.Ignore(e => e.Path);
}
}
and then changed the code that created the new entity to make user of the new context type
using (var specialContext = new _navPropInhibitingContext())
{
var dbModel = new MyEntity()
{
...
};
specialContext.MyEntity.Add(dbModel);
await specialContext.SaveChangesAsync();
}
Hope this helps somebody
I have the same issue.
Here is my case, if you are adding a new record and has a primary key but is not auto-incremented, this will trigger an error.
I thought first that it will automatically generate the key for me so I leave the Id as blank.
Example:
Customer cust = new Customer();
//cust.Id - I left it blank
db.Customer.Add(cust);
db.SaveChanges();
But upon quick investigation, I forgot to set it's Identity to true and that would trigger an error once you do SaveChanges on your DbContext.
So make sure if your Identity is true or not.
In my case I was passing auto generated primary key of the same table in foreign key column so entity frame work is throwing an error that it can not set a value of that column which is not generated yet as we can only get autogenerated value after save change
Here BonusRequestId is my primary key which I was doing a mistake
Working on a project where I have more or less carte blanche to modify the database schema and object model (nice position to be in. (c:) Suppose I have a trivial inheritance tree like:
class Parent
{
public int ID { get; set; }
}
class Child : Parent
{
// some fields
}
Is it better to have a database schema where the child ID and the parent ID are the same (e.g., parent primary key is IDENTITY(1,1), child primary key is assigned and is a NOT NULL foreign key to the parent table), or should the child table maintain its own primary key and keep its reference to the parent table in another field? What are the considerations to be made in this case? What are the pro's and con's of each approach? NHibernate supports both, right?
I would let the child have it's own id. It'd be useless information but that detriment is far outweighed by the fact that it would be an easily recognizable 1-to-1 relationship rather than a "How the heck does this work?" relationship.
And yes, nHibernate can handle one-to-one relationships.