Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

entity framework 6 - How to set the one-to-one relationship with fluent api in this case? (EF6)

I have this two entities:

    public partial class Ficheros
        {
            public Guid Idfichero { get; set; }
            public long Iddocumento { get; set; }
            public byte[] Fichero { get; set; }

            public virtual Documentos IddocumentoNavigation { get; set; }
        }

public partial class Documentos
    {
        public Documentos()
        {
            ElementosDocumentos = new HashSet<ElementosDocumentos>();
        }

        public long Iddocumento { get; set; }
        public string Nombre { get; set; }
        public long? IdtipoDocumento { get; set; }
        public string Codigo { get; set; }
        public decimal? Espacio { get; set; }
        public string Unidades { get; set; }
        public long? Bytes { get; set; }

        public virtual ICollection<ElementosDocumentos> ElementosDocumentos { get; set; }
        public virtual Ficheros Ficheros { get; set; }
        public virtual DocumentosTipos IdtipoDocumentoNavigation { get; set; }
    }

In the database, IDFichero is an uniqueidentifier and in Documentos the IDDocumento is a big int autoincrement. The main table is Documentos, that has one and only one fichero, and it is requiered.

The examples that I have seen, it would make me that IDFichero was IDDocumento, but to store a file in the database I need that the ID is a uniqueidentifier.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The relationship you are describing in EF terms is one-to-one FK association with both ends required, Documentos being the principal and Ficheros the dependent.

EF does not support explicit FK for this type of association, so start by removing the Ficheros.Iddocumento property:

public partial class Ficheros
{
    public Guid Idfichero { get; set; }
    public byte[] Fichero { get; set; }

    public virtual Documentos IddocumentoNavigation { get; set; }
}

then use the following fluent configuration:

modelBuilder.Entity<Documentos>()
    .HasRequired(e => e.Ficheros)
    .WithRequiredPrincipal(e => e.IddocumentoNavigation)
    .Map(m => m.MapKey("Iddocumento"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...