D
D
Dmitry Donskoy2015-12-19 04:11:45
ASP.NET
Dmitry Donskoy, 2015-12-19 04:11:45

How to make one to zero/one in Entity Framework?

There is a main table accounts, which includes various services.
Services have a ratio to this account as 1 to 0/1,
i.е. The account must be, and the service may or may not be.

public class ApplicationUser : IdentityUser<long, VRSIdentityUserLogin, VRSIdentityUserRole, VRSIdentityUserClaim>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override long Id { get; set; }
public long Balance { get; set; }
public virtual ServiceEntity1 ServiceEntity{ get; set; }
public virtual ServiceEntity2 ServiceEntity{ get; set; }
}

Services must have data bound to them, some one-to-one, others one-to-many.
public class ServiceEntity1 
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public ApplicationUser  User { get; set; }
public virtual  Metrica ServiceMetrica{ get; set; }
public virtual  List<ModuleService> ServiceModules{ get; set; }
}

public class Metrica
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long id { get; set; }

public virtual long ServiceEntityId { get; set; }
public virtual ServiceEntity1 ServiceEntity { get; set; }
}

It is also necessary that the ApplicationUser.Id be generated by the database and used in ServiceEntity1.Id, which in turn is the key for Metrica.ServiceEntityId

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2015-12-19
@yarosroman

public class ServiceEntity1 
{
[Key, ForeignKey("ApplicationUser")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public ApplicationUser  User { get; set; }

P
Pavel Elizariev, 2015-12-19
@effetto

Use the notation "type?" for the secondary key. For example: Guid? or int?. EF will automatically figure out what you want 0..1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question