I have two tables
CREATE TABLE Company (
Id uniqueidentifier primary key not null,
CompanyName nvarchar(100) not null)
GO
CREATE TABLE Feature (
Id uniqueidentifier primary key not null,
CompanyId uniqueidentifier not null,
Feature1 bit not null,
Feature2 bit not null)
GO
How to make one to one relation by CompanyId field on database and EF Code First side with configuration files
The classes:
public class Company
{
private Guid id = Guid.NewGuid();
public virtual Guid Id
{
get { return id; }
set { id = value; }
}
public virtual string CompanyName { get; set; }
}
public class Feature
{
private Guid id = Guid.NewGuid();
public virtual Guid Id
{
get { return id; }
set { id = value; }
}
public virtual Company Company { get; set; }
public virtual bool Feature1 { get; set; }
public virtual bool Feature2 { get; set; }
}
You cannot make a real one-to-one relation in EF with these tables because it requires unique index on
CompanyIdcolumn and EF doesn’t support unique indices yet. Currently the only way to get a real one-to-one relation is to use primary key of dependent table (in your caseFeature.Id) as foreign key to principal table.You can cheat. Just use it as one-to-many (Company can have many features) and if you have unique index in the database you will receive exception if another feature tries to associate with already used company.